Python-Opencv,获取颜色最主要的图像区域吗?

时间:2018-12-09 12:25:52

标签: python opencv hsv

我有一段代码可以检测红色的存在,然后将帧划分为2个ROI,然后在每个这些区域中应用一个蒙版,因此我在末尾使用了代表颜色的位置找到其余的零,这适用于所有区域。

我知道如何找到具有红色优势的区域? 我该怎么办?

import cv2
import math
import numpy as np

Video = cv2.VideoCapture(0)
while True:
    _, img = Video.read()
    # detect red lines
    # =======================================
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    min = np.array([150, 40, 40])
    max = np.array([190, 255, 255])
    mask = cv2.inRange(hsv, min, max)
    height, width = img.shape[:2]

    res1 = cv2.bitwise_and(img, img, mask=mask)
    #res1= cv2.cvtColor(res1,cv2.COLOR_BGR2GRAY)
    roi1 = res1[0:height, 0:width / 2]
    roi2 = res1[0:height, width / 2:width]

    cv2.imshow("part1", roi1)
    cv2.imshow("part2", roi2)

    k = cv2.waitKey(2) & 0xFF
    if k == 27 or k == 'q':
        break
Video.release()
cv2.destroyAllWindows()

我尝试这样做

 roi1 = img[0:height, 0:width / 2]
 roi2 = img[0:height, width / 2:width]
 res1 = cv2.bitwise_and(roi1, roi1, mask=mask)
 res2 = cv2.bitwise_and(roi2, roi2, mask=mask)

但是我得到的错误是这个

  

res1 = cv2.bitwise_and(roi1,roi1,mask = mask)   cv2.error:OpenCV(3.4.2)C:\ projects \ opencv-python \ opencv \ modules \ core \ src \ arithm.cpp:241:error:(-215:Assertion failed)(mtype == 0 || mtype == 1)&& _mask.sameSize(* psrc1)在函数'cv :: binary_op'

我想如果没有那个错误,我可以直接比较res1和res2的值吗?

=======================

编辑,我尝试了此方法,但它确实起作用,但是我有感觉可以做得更好?

roi1 = cv2.cvtColor(roi1, cv2.COLOR_HSV2BGR)
roi2 = cv2.cvtColor(roi2, cv2.COLOR_HSV2BGR)

roi1_h, roi1_w = roi1.shape[:2]
roi2_h, roi2_w = roi1.shape[:2]
R1 = 0
R2 = 0

w = cv2.waitKey(3) & 0xFF

if w == ord('a'):


    for i in range(roi1_h - 1):
        for j in range(roi1_w - 1):
            k = roi1[i, j]
            z = roi2[i, j]
            R1 += k[0]+k[1]+k[2]
            R2 += z[0]+z[1]+z[2]

print(R1)
print(R2)

0 个答案:

没有答案