python - 具有定义边缘的 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)
蒙面和未蒙面的屏幕截图
左边的图像是原始截图,右边的图像是蒙版。
解决方案
要在图像中查找红色矩形区域,您可以执行以下操作:
- 提取图像的红色通道
- 阈值红色通道
- 计算非零像素的数量
示例代码:
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)
推荐阅读
- r - R plotly极坐标图中刻度标签的注释/文本
- c# - JWT 验证在 .NET Core 中有效,在 .NET Framework 中失败
- tcsh - TCSH - most compact sytax for checking if value in an array/list?
- google-bigquery - 支持使用 KNIME 的 Google BigQuery JDBC 驱动程序
- html - div 消失,移除高度限制
- applescript - 如何处理从 AppleScript 中的结果返回的列表?
- sql - 如何在将 EntityManager 与 Hibernate 一起使用时使用 IN 子句
- android - 选项卡在 NestedScrollview 中的 Recyclerview 中分段
- php - Foreach 循环,有大量的变量
- vue.js - 将箭头键绑定到 Buefy 分页