首页 > 解决方案 > 计算 cv2.circle 内的白色像素

问题描述

我正在尝试使用 python 和 openCV 实现视神经胶质瘤的识别。

我需要执行以下步骤才能成功对视神经胶质瘤进行分类。

  1. 找到图像的最亮部分并使用 cv2.circle 在其上放置一个圆圈 -完成
  2. 计算 cv2.circle 内图像上的白色部分 -需要帮助

这是我识别图像最亮部分的代码

gray = cv2.GaussianBlur(gray, (371, 371), 0)
(minVal, maxVal, minLoc, maxLoc) = cv2.minMaxLoc(gray)
image = orig.copy()
cv2.circle(image, maxLoc, 371, (255, 0, 0), 2)

sought = [254,254,254]
amount = 0

for x in range(image.shape[0]):
    for y in range(image.shape[1]):
        b, g, r = image[x, y]
        if (b, g, r) == sought:
            amount += 1

print(amount)

image = imutils.resize(image, width=400)

# display the results of our newly improved method
cv2.imshow("Optic Image", image)
cv2.waitKey(0)

上面的代码返回以下输出

在此处输入图像描述

我现在要做的是确定 cv2.circle 内图像的白色区域的大小。

太感谢了!

标签: pythonopencv

解决方案


我不确定您认为什么是“白色”,但这是在 Python/OpenCV 中进行计数的一种方法。只需阅读图像。转换为灰度。将其限制在某个级别。然后只需计算阈值图像中白色像素的数量。

如果我使用你的输出图像作为我的输入(在删除你的白色边框之后):

在此处输入图像描述

import cv2
import numpy as np

# read image
img = cv2.imread('optic.png')

# convert to HSV and extract saturation channel
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

# threshold
thresh = cv2.threshold(gray, 175, 255, cv2.THRESH_BINARY)[1]

# count number of white pixels
count = np.sum(np.where(thresh == 255))
print("count =",count)

# write result to disk
cv2.imwrite("optic_thresh.png", thresh)

# display it
cv2.imshow("IMAGE", img)
cv2.imshow("THRESH", thresh)
cv2.waitKey(0)


阈值图像:

在此处输入图像描述

阈值中的白色像素数:

count = 1025729



推荐阅读