cv2.PCACompute()在灰色图像背景上查找明亮和黑暗的对象

时间:2018-09-07 10:30:06

标签: python opencv cv2

我想在图像上找到对象并在其轴上画一条红线。问题是有明亮物体和黑暗物体的图像。图像的照明不是最佳的。我可以调整cv2.threshold()中的值以使程序找到明亮或黑暗的物体,但是如何找到两者呢?我想到了一个if语句,但是会是什么样?

代码:

    img = cv2.imread('image.png')
    img_gs = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    img_gs = cv2.GaussianBlur(img_gs,(5,5),0)
    _, thresh = cv2.threshold(img_gs,
                              0,
                              255,
                              cv2.THRESH_BINARY+cv2.THRESH_OTSU)
    mat = np.argwhere(thresh != 0)
    mat[:, [0, 1]] = mat[:, [1, 0]]
    mat = np.array(mat).astype(np.float32)
    m, e = cv2.PCACompute(mat, mean = np.array([]))
    center = tuple(m[0])
    endpoint1 = tuple(m[0] + e[0]*100)
    endpoint3 = tuple(m[0] - e[0]*100)
    red_color = (0, 0, 255)
    cv2.circle(img, center, 5, red_color)
    cv2.line(img, center, endpoint1, red_color)
    cv2.line(img, center, endpoint3, red_color)
    cv2.imwrite('savedimage.png', img)

ErrorMessage:

m, e = cv2.PCACompute(mat, mean = np.array([]))
cv2.error: OpenCV(3.4.2) /io/opencv/modules/core/src/matmul.cpp:2557: error: (-215:Assertion failed) nsamples > 0 in function 'calcCovarMatrix'

良好形象:

enter image description here

图片不良(错误消息):

enter image description here

结果应为:

enter image description here

0 个答案:

没有答案