Search code examples
pythonimagepycharmdistancedetection

Detecting maximum pixel distance in a image


I'm a beginner at python and pycharm. I have a question while working on the project

Can you tell me how to make the code for detecting maximum distance in a image just as below? I saw some code using MATLAB in the previous post, but I wonder how to make it with python code.

My goal is to draw a line (just like a red line in post below.) and mark its distance in the image.

post : http://georgepavlides.info/how-to-detect-the-maximum-pixel-distance-in-a-binary-image/


Solution

  • I wrote this code and hope it solve your problem:

    from PIL import Image
    import math
    
    im = Image.open('C:\\pic\\1.jpg') # Can be many different formats.
    pix = im.load()
    rgb_im = im.convert('RGB')
    
    ls_white=[]
    
    for i in range(rgb_im.size[0]):
        for j in range(rgb_im.size[1]):
            if(rgb_im.getpixel((i, j))!=(0,0,0)):
                ls_white.append((i,j))      
    
    max_distance=-1
    
    for i in range(len(ls_white)):
        for j in range(i+1,len(ls_white)):
            distance=math.dist(ls_white(i),ls_white(j))>max_distance
            if(distance>max_distance):
                max_distance=distance
    

    I test it for 50px*30px (1500 pixels) image and it worked.

    Remmber: for large images it may get your memory full, so you have to make some optimization and remove some impure pixels.

    First I get any pixel that has color not equal to Black, and save it's position into ls_white.

    Second I check distance from first point in ls_white to others, and do it for other pixels, and if distance is bigger, will save it to max_distance.

    I propose that try it from a tiny simple picture with few number of white points.

    sample image I made for test of my code