簡體   English   中英

獲取圖像中每個對象的像素數

[英]Get number of pixels of each object in image

如圖所示,我有一個蒙版 MRI,其中某些肌肉已被分割。 我正在嘗試以像素為單位獲取這些肌肉的面積。 目前,我可以使用np.count_nonzero(result)獲取圖像中的所有非零像素,但是,我希望獲取左右肌肉的各個區域,而不僅僅是總數。

我知道我可以手動裁剪/選擇每個區域的 ROI,但我不想對 100 多張圖像執行此操作。 也不是所有的肌肉都像底部圖像那樣清晰地出現在每一側(不能將圖像分成兩半)。 圖像表示為二維數組。

謝謝!

在此處輸入圖像描述 在此處輸入圖像描述

您可以使用OpenCV庫獲取圖像中每個對象的像素數。

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()

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM