gpt4 book ai didi

python - 在 python 中使用 opencv 显示图像中特定颜色周围的边界

转载 作者:太空宇宙 更新时间:2023-11-03 23:10:51 24 4
gpt4 key购买 nike

实际上我正在使用 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()

我能够找到红色,但我对检测颜色出现区域的位置有些困惑。谢谢

最佳答案

您可以在 mask 上使用 numpy.where() 获取坐标列表。 mask 是单 channel 图像,红色区域为 [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 - 在 python 中使用 opencv 显示图像中特定颜色周围的边界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50516127/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com