我怎么知道在Python中使用OpenCV检测到的白色区域的位置?

时间:2017-01-29 09:19:03

标签: python opencv image-processing

例如,在此代码中,我已过滤了视频Feed以显示白色区域。我怎么知道他们的位置/坐标?(x,y)

import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while(1):
    _, frame = cap.read()
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    # define range of white color in HSV
    # change it according to your need !
    lower_white = np.array([0,0,0], dtype=np.uint8)
    upper_white = np.array([0,0,255], dtype=np.uint8)

    # Threshold the HSV image to get only white colors
    mask = cv2.inRange(hsv, lower_white, upper_white)
    # Bitwise-AND mask and original image
    res = cv2.bitwise_and(frame,frame, mask= mask)
    cv2.imshow('frame',frame)
    cv2.imshow('mask',mask)
    cv2.imshow('res',res)

    k = cv2.waitKey(5) & 0xFF
    if k == 27:
        break

cv2.destroyAllWindows()

2 个答案:

答案 0 :(得分:0)

你可以使用numpy方法获取矩阵中不为零的所有值。

indcies = numpy.nonzero(res)

答案 1 :(得分:0)

根据Amitay的回答,您还可以使用OpenCV的功能findNonZero。我不知道它的实现方式与numpy的nonzero有什么不同,但是如果给出的结果相同而且速度更快(对大型循环或图像有用)

import cv2
import numpy as np
import time 

so=cv2.imread(your_image,0)

start1=time.clock()
coord=cv2.findNonZero(so)
end1=time.clock()

start2=time.clock()
coord2=np.nonzero(so)
end2=time.clock()

print("cv2.findNonZeros() takes "+str(end1-start1)+" seconds.")
print("np.nonzero() takes       "+str(end2-start2)+" seconds.")

>>> cv2.findNonZeros() takes 0.003266 seconds.
>>> np.nonzero() takes       0.021132 seconds.