简体   繁体   English

具有定义边缘的Python 3 OpenCV颜色对象检测

[英]Python 3 OpenCV Color Object Detect with defined edges

My python code takes a screenshot of by desktop and looks for a red rectangle on a black background, when I use the cv2.findcountours it doesn't return an exact sized rectangle, it seems to be distorted. 我的python代码通过桌面截图,并在黑色背景上寻找红色矩形,当我使用cv2.findcountours时,它没有返回确切大小的矩形,它似乎失真了。 I would like to obtain the exact area of the shape. 我想获取形状的确切区域。 Also, the image on my screenshot has no pixelation and borders are sharp. 另外,屏幕快照上的图像没有像素,边框也很清晰。 Thanks for your help! 谢谢你的帮助!

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)

screenshot of the masked and unmasked 已屏蔽和未屏蔽的屏幕截图

在此处输入图片说明

The image on the left is raw screenshot and the image on the right is the masked. 左侧的图像是原始屏幕截图,右侧的图像是蒙版。

To find area of red rectangle in the image you can do as: 要在图像中找到红色矩形的区域,您可以执行以下操作:

  • extract red channel of the image 提取图像的红色通道
  • threshold red channel 阈值红色通道
  • count number of nonzero pixels 计算非零像素数

Example code: 示例代码:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM