Home > Software engineering >  Get number of pixels of each object in image
Get number of pixels of each object in image

Time:12-20

As shown in the images, I have a masked MRI in which certain muscles have been segmented out. I am trying to get the area of these muscles in pixels. Currently, I can get all the non-zero pixels in the image using np.count_nonzero(result), however, I am looking to get the individual areas of each left and right muscle, not just the total.

I know I can manually crop/select an ROI of each area, but I do not want to do this for 100s of images. Also not all muscles are cleanly on each side as seen by the bottom image (cannot just split the image in half). The images are represented as 2D arrays.

Thank you!

enter image description here enter image description here

CodePudding user response:

You can use OpenCV Library to get the number of pixels for each object in the image.

import cv2 # OpenCV library

# Read the image
image = cv2.imread(r'D:\image_sample.jpg')

# Convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Get the mask (predefined threshold)
mask = cv2.inRange(gray, 200, 255)

#Find all Objects contour's 
contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

for i in range(len(contours)):
    m=max(contours[i][0])
    area = cv2.contourArea(contours[i])
    print(f"Area{i 1} = {area} pixels")
    image = cv2.drawContours(image, contours, i, (0,255,255*i), -1)
    img_text = cv2.putText(image, str(area), m, cv2.FONT_HERSHEY_PLAIN, 1, (255,0,255), 1, cv2.LINE_AA, False)
        
#Show the resut
cv2.imshow('image with contours', image)
cv2.waitKey()

enter image description here

  • Related