python - 在 python 中使用 opencv 在图像中显示特定颜色周围的边界
问题描述
实际上我正在使用opencv在python中进行颜色检测,我想在红色周围显示一个边界这是我的python代码。
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
while(1):
_, frame = cap.read()
frame=np.fliplr(frame)
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
lower_red = np.array([0,170,175])
upper_red = np.array([20,255,255])
mask = cv2.inRange(hsv, lower_red, upper_red)
res = cv2.bitwise_and(frame,frame, mask= mask)
kernel = np.ones((15,15),np.float32)/225
smoothed = cv2.filter2D(res,-1,kernel)
cv2.imshow('Original',frame)
cv2.imshow('Averaging',smoothed)
_, puck = cv2.threshold(smoothed, 30, 255, cv2.THRESH_BINARY)
cv2.imshow('Puck',puck)
k = cv2.waitKey(5) & 0xFF
if k == 27:
break
cv2.destroyAllWindows()
cap.release()
我能够找到红色,但我对检测颜色发生区域的位置有些困惑。谢谢
解决方案
numpy.where()
您可以使用on获取坐标列表mask
。mask
是单通道图像,在红色区域上具有 [255],在没有红色区域上具有 [0]
indices = np.where(mask!= [0])
coordinates = zip(indices[0], indices[1])
- 我使用 numpy.where() 方法检索两个数组的元组索引,其中第一个数组包含白点的 x 坐标,第二个数组包含白色像素的 y 坐标。
indices
返回:
(array([375, 375, 375, ..., 915, 915, 915], dtype=int64),
array([496, 497, 498, ..., 420, 421, 422], dtype=int64))
- 然后,我使用该
zip()
方法获取包含红色坐标的元组列表。
打印坐标给了我一个红色的坐标列表
推荐阅读
- python - 为什么将列表分配给另一个列表会产生“无”?
- jquery - 如何从json中获取事件
- html - 在 bootstrap 4 中使用类行时将元素放在页面右侧
- function - 如果成员函数存在,如何引用或调用成员函数
- c# - 字符串替换为空字符
- sql - 从 ISO 周 (201905) BigQuery 中提取日期
- flutter - 在 Android 中启动更新后 Flutter 应用程序崩溃
- php - 如何使用“.htaccess”删除图像 URL 的子文件夹?
- r - 使用 R 的非嵌套模型比较
- javascript - X-editable Yii2:未捕获的类型错误:无法读取 null 的属性“substr”