pythonimage-masking

Consecutive Image Masking in Python


I am working on a project to mask consecutive images at different positions to study the movement of a single fly. The final image should look like this: correct masking of image. However, as the code continues to run, the images start to turn out like this: Incorrect image masking, which is not what I want because I only want one visible region (circle containing a single fly) per image rather than three. What do I need to do to my code so that only one circle is present in each image at different positions rather than there being multiple circles in an image?

`List = [
    [180, 353, 85, str("/media/pi/T3 1TB 2Ch xFer/Ramzy Masked /Arena2")],
    [180, 542, 85, str("/media/pi/T3 1TB 2Ch xFer/Ramzy Masked /Arena3")],
    [180, 728, 85, str("/media/pi/T3 1TB 2Ch xFer/Ramzy Masked /Arena4")],
]

def load_images_from_folder(folder):
    images = []
    for filename in os.listdir(folder):
        img = cv2.imread(os.path.join(folder,filename))
        mask = np.zeros(img.shape[:2], dtype="uint8")
    
        for row in List:
            cv2.circle(mask, (row[0], row[1]), row[2], 255, -1)
            masked = cv2.bitwise_and(img, img, mask=mask)
            cv2.imwrite(os.path.join(row[3], f'{filename}'),  masked)

load_images_from_folder("/media/pi/T3 1TB 2Ch xFer/Ramzy Research 
Photos/8.17.21")
    
cv2.waitKey(0)
cv2.destroyAllWindows()

`


Solution

  • I am not overly familiar with the cv2 library but I believe that this line:

    cv2.circle(mask, (row[0], row[1]), row[2], 255, -1)
    

    Is adding a new circle onto your mask at every loop. There are a bunch of ways to fix this, but you could begin with moving this line to just above the cv2.circle call in the loop like such:

    def load_images_from_folder(folder):
        images = []
        for filename in os.listdir(folder):
            img = cv2.imread(os.path.join(folder,filename))
        
            for row in List:
                mask = np.zeros(img.shape[:2], dtype="uint8")
                cv2.circle(mask, (row[0], row[1]), row[2], 255, -1)
                masked = cv2.bitwise_and(img, img, mask=mask)
                cv2.imwrite(os.path.join(row[3], f'{filename}'),  masked)
    
    

    This will create a brand new mask on each loop iteration.