首页 > 解决方案 > 在 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()

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

标签: pythonopencvcolors

解决方案


numpy.where()您可以使用on获取坐标列表maskmask是单通道图像,在红色区域上具有 [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()方法获取包含红色坐标的元组列表。

打印坐标给了我一个红色的坐标列表


推荐阅读