首页 > 解决方案 > 具有定义边缘的 Python 3 OpenCV 颜色对象检测

问题描述

我的 python 代码通过桌面截取屏幕截图并在黑色背景上查找红色矩形,当我使用 cv2.findcountours 时,它没有返回精确大小的矩形,它似乎被扭曲了。我想获得形状的确切面积。此外,我的屏幕截图上的图像没有像素化,边框清晰。谢谢你的帮助!

frame_TS_new_raw = np.array(sct.grab(monitor_TS_new))
frame_TS_new = cv2.cvtColor(frame_TS_new_raw, cv2.COLOR_RGBA2RGB)

green_mask_TS_new = cv2.inRange(frame_TS_new,green_lower_range, green_upper_range)

# find contours for New TS
cnts_green_new = cv2.findContours(green_mask_TS_new.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cnts_green_new = cnts_green_new[0] if imutils.is_cv2() else cnts_green_new[1]
if len(cnts_green_new) > 0:
    for c in cnts_green_new:
        # if the contour is not sufficiently large, ignore it
        if cv2.contourArea(c) > 100:
            area = cv2.contourArea(c)

蒙面和未蒙面的屏幕截图

在此处输入图像描述

左边的图像是原始截图,右边的图像是蒙版。

标签: pythonopencv

解决方案


要在图像中查找红色矩形区域,您可以执行以下操作:

  • 提取图像的红色通道
  • 阈值红色通道
  • 计算非零像素的数量

示例代码:

import cv2
import numpy as np

img = cv2.imread('vju0v.png')
img = np.array(img) # convert to numpy array
red = img[:,:,2]    # extract red channel
rect = np.float32(red > 200)   # find red pixels
area = np.sum(rect)    # count nonzero pixels

print('Area = ' + str(area))

cv2.imshow('Red Channel',rect)
cv2.waitKey(0)

推荐阅读