【问题标题】:OpenCV average intensity of contour figures in grayscale image灰度图像中轮廓图的OpenCV平均强度
【发布时间】:2020-08-18 21:16:37
【问题描述】:

有了这个人造图像,我可以找到这些数字并为其创建一个蒙版,然后使用两个丑陋的 for 循环计算它们的平均强度(灰度),这会消耗大量时间,并且图像中有相当数量的数字。

#!/usr/bin/env python3
import imutils
import cv2
import numpy as np
from scipy.stats import norm

image = cv2.imread("./test_images/test_artificial2.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Noise reduction
blurred = cv2.GaussianBlur(gray, (3, 3), 0)

# thresholding
mean, std=norm.fit(blurred)
thresh_min_value = int(mean + 3.6*std)
thresh = cv2.threshold(blurred, thresh_min_value, 255, cv2.THRESH_BINARY)[1]

# find contours in the thresholded image
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
        cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)

for c in cnts:
    # Moments
    M = cv2.moments(c)
    # Area of contour
    area = M["m00"]

    # Centroid of contour
    cX = int(M["m10"] / M["m00"])
    cY = int(M["m01"] / M["m00"])

    # Perimeter
    perimeter = cv2.arcLength(c, True)

    print(f'{area=}')
    print(f'{perimeter=}')

    epsilon = 0.02 * perimeter
    approx = cv2.approxPolyDP(c, epsilon, True)
    print(f'{approx=}')

    # Create blank mask
    mask_contour = np.zeros(gray.shape, np.uint8)

    # Draw contour in the mask
    cv2.drawContours(mask_contour, [approx], -1, (255, 255, 255), -1)

    # This calculates the intensity of the polygon correctly
    intensity = []
    for i in range(0, gray.shape[0]):
        for j in range(0, gray.shape[1]):
            if mask_contour[i][j] == 255:
                intensity.append(gray[i][j])

    print(sum(intensity)/len(intensity))

    # But I would like to speed up the process somehow
    #masked_image = np.where(mask_contour == 255, gray, 0)
    #average_intensity = np.mean(masked_image)
    # print(f'{average_intensity=}')

    cv2.imshow("Image", mask_contour)
    cv2.waitKey(0)

正如在一条评论中已经建议的那样,我可以使用 NumPy 来计算它的平均强度,但我不能让它只用图形的像素来计算它,它会添加其余的像素。

是否有可能用其他更快的方法来实现这一点?

谢谢。

【问题讨论】:

  • 请显示您的输入图像,不带任何轮廓或多边形。 1)它只是多边形的顶点。 2)为每个轮廓或多边形创建一个蒙版(在黑色背景上绘制白色填充)。然后使用遮罩来限制用于获取平均值的像素区域。平均值=np.mean(np.where(mask==255))
  • @fmw42 首先感谢您的回答,因为第 2 点非常有帮助,关于您最初的评论,我提供的图片是原始图片(我人工制作以进行更好的测试),正在运行带有该图像的代码应该显示我在问题中提出的问题
  • @fmw42 你能详细说明你的答案吗?我正在尝试这个: mask_contour = np.zeros(gray.shape, np.uint8); cv2.drawContours(mask_contour, [近似], -1, (255, 255, 255), -1); masked_contour = cv2.bitwise_and(灰色,灰色,mask=mask_contour)。此时我在多边形区域有一个零和 255 的蒙版,我如何告诉 numpy 使用此蒙版获得灰度图像的平均值?谢谢。
  • 既然它们的尺寸相同,你就不能gray[mask_contour==255].mean()吗?
  • @imochoa 你是完全正确的,这也有效,可能是最好的答案,谢谢。

标签: python image numpy opencv


【解决方案1】:

所以,最后,这是一个可行的解决方案,再次感谢@fmw42 为我指明了正确的方向,并感谢@imochoa 提供了最短的工作代码。

#!/usr/bin/env python3
import imutils
import cv2
import numpy as np
from scipy.stats import norm

image = cv2.imread("./test_images/test_artificial2.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Noise reduction
blurred = cv2.GaussianBlur(gray, (3, 3), 0)

# thresholding
mean, std = norm.fit(blurred)
thresh_min_value = int(mean + 3.6*std)
thresh = cv2.threshold(blurred, thresh_min_value, 255, cv2.THRESH_BINARY)[1]

# find contours in the thresholded image
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
        cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)

for c in cnts:
    # Moments
    M = cv2.moments(c)
    # Area of contour
    area = M["m00"]

    # Centroid of contour
    cX = int(M["m10"] / M["m00"])
    cY = int(M["m01"] / M["m00"])

    # Perimeter
    perimeter = cv2.arcLength(c, True)

    print(f'{area=}')
    print(f'{perimeter=}')

    epsilon = 0.02 * perimeter
    approx = cv2.approxPolyDP(c, epsilon, True)
    print(f'{approx=}')

    # Create blank image
    blank_image = np.zeros(gray.shape, np.uint8)

    # Draw contour in the mask
    cv2.drawContours(blank_image, [approx], -1, (255, 255, 255), -1)

    # Create a mask to select pixels inside the figure
    mask_contour = blank_image == 255

    # Calculate the intensity from the grayscale image
    # filtering out the pixels where in the blank_image their value is not 255
    intensity = np.mean(gray[mask_contour])
    print(f'{intensity=}')

    cv2.imshow("Image", blank_image)
    cv2.waitKey(0)

【讨论】:

    猜你喜欢
    • 2020-02-19
    • 2022-01-11
    • 2012-11-06
    • 2013-07-29
    • 1970-01-01
    • 2020-09-29
    • 2016-08-09
    • 2014-11-29
    • 1970-01-01
    相关资源
    最近更新 更多