首页 > 解决方案 > 如何用python找到图像中圆形的平均RGB值?

问题描述

我正在尝试帮助一位使用非常古老的比色技术来测量细胞死亡的同事。为了简化问题,这里是一个示意图:

在此处输入图像描述

这被称为 96 孔板。我需要找到所有的井并返回每个井的 RGB 值。粉红色表示所有细胞都活着,蓝色表示没有细胞活着。他们有一个计算公式。现在我一直在处理这张图片,到目前为止我可以用这段代码检测所有的井:

import cv2 
import numpy as np 

# Read image. 
img = cv2.imread('images/placaTeoricaCompleta_result.jpg') 

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

# Blur using 3 * 3 kernel. 
gray_blurred = cv2.blur(gray, (3, 3))


# Apply Hough transform on the blurred image. 
detected_circles = cv2.HoughCircles(gray_blurred, 
                cv2.HOUGH_GRADIENT, 1.2, 20, param1 = 50, 
            param2 = 30, minRadius = 30, maxRadius = 50) 

# Draw circles that are detected. 
if detected_circles is not None: 

    # Convert the circle parameters a, b and r to integers. 
    detected_circles = np.uint16(np.around(detected_circles))

    for pt in detected_circles[0, :]: 
        a, b, r = pt[0], pt[1], pt[2] 

        # Draw the circumference of the circle. 
        cv2.circle(img, (a, b), r, (0, 255, 0), 2) 

        # Draw a small circle (of radius 1) to show the center. 
        cv2.circle(img, (a, b), 1, (0, 0, 255), 3) 
    
    cv2.imshow("Detected Circle", img) 
    cv2.waitKey(0) 

但我找不到返回每口井的 RGB 值的方法。

真实的图像看起来像这样:

在此处输入图像描述

如何返回每个圆圈的 RGB 值?这将优选地按照从 A 到 H 和从 1 到 12 的顺序,或者以其他方式将 RGB 值写入圆圈中。

标签: pythonopencvimage-processing

解决方案


您可以为每个圆圈生成一个蒙版,然后获得颜色通道的平均值。以下代码仅用于一个循环,但您可以将其放入 for 循环中:

x, y, r = detected_circles[0].astype(np.int32)
roi = image[y - r: y + r, x - r: x + r]

感兴趣的区域

# generate mask
width, height = roi.shape[:2]
mask = np.zeros((width, height, 3), roi.dtype)
cv2.circle(mask, (int(width / 2), int(height / 2)), r, (255, 255, 255), -1)

面具

dst = cv2.bitwise_and(roi, mask)

蒙版图像

# filter black color and fetch color values
data = []
for i in range(3):
    channel = dst[:, :, i]
    indices = np.where(channel != 0)[0]
    color = np.mean(channel[indices])
    data.append(int(color))

# opencv images are in bgr format
blue, green, red = data # (110, 74, 49)

最终图像

图像中的文本为 rgb 格式。


推荐阅读