如何使用HSV获得最小的颜色轮廓?

时间:2019-11-01 05:13:59

标签: image-processing data-extraction hsv color-tracking

我正在尝试图像处理。因此,在选择最小面积for pic, contour in enumerate(contours):

之后,我需要在if (area > 2000):下抓取轮廓的最大和最小面积

我可以在for loop之外获取轮廓的最大值和最小值,这是我需要在此代码中最小轮廓大于2000的问题。

我的完整代码:

import cv2
import numpy as np
from imutils.video import FPS

import time

cap = cv2.VideoCapture(0)

width = cap.get(3)  # float
height = cap.get(4)  # float
print width, height
time.sleep(2.0)
fps = FPS().start()
while (1):
    _, img = cap.read()

    if _ is True:
        hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    else:
        continue


    blue_lower = np.array([86,0,90], np.uint8)
    blue_upper = np.array([163, 64, 145], np.uint8)
    blue = cv2.inRange(hsv, blue_lower, blue_upper)
    kernal = np.ones((9, 9), "uint8")
    blue = cv2.dilate(blue, kernal)
    res_blue = cv2.bitwise_and(img, img, mask=blue)

    (_, contours, hierarchy) = cv2.findContours(blue, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    for pic, contour in enumerate(contours):
        area = cv2.contourArea(contour)
        if (area > 2000):
            print area
            x, y, w, h = cv2.boundingRect(contour)
            img = cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
            cv2.putText(img, "Blue Colour", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 0, 0))
    if len(contours) > 0:
        c = max(contours, key=cv2.contourArea)

        x, y, w, h = cv2.boundingRect(c)
        img = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 0), 5)
        cv2.putText(img, "Blue Colour", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0))

    cv2.imshow("Color Tracking", img)
    if cv2.waitKey(10) & 0xFF == ord('q'):
        cap.release()
        cv2.destroyAllWindows()
        break
    fps.update()

任何想法或建议都会受到赞赏

0 个答案:

没有答案
相关问题