如何使用opencv轨道栏限制三种颜色?

时间:2017-05-27 14:06:28

标签: python opencv

我有一个任务说"使用轨迹栏的三种颜色阈值。将blob绘制为相应的颜色。"

我创建了轨道栏并且它们工作正常,但我该如何完成此任务?不幸的是,他们没有在课堂上给我们足够的信息来解决它。

非常感谢您的合作。

import numpy as np
import cv2

# open the camera
cap = cv2.VideoCapture(0)

def nothing(x):
    pass
cv2.namedWindow('result')

# Starting with 100's to prevent error while masking
h,s,v = 100,100,100

# Creating track bar


cv2.createTrackbar('h', 'result',0,179,nothing)
cv2.createTrackbar('s', 'result',0,255,nothing)
cv2.createTrackbar('v', 'result',0,255,nothing)

while True:

        #read the image from the camera
        ret, frame = cap.read()        

        #You will need this later
        frame = cv2.cvtColor(frame, 35)



        #converting to HSV
        hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)


        # get info from track bar and appy to result
        h = cv2.getTrackbarPos('h','result')
        s = cv2.getTrackbarPos('s','result')
        v = cv2.getTrackbarPos('v','result')


        # Normal masking algorithm
        lower_blue = np.array([h,s,v])
        upper_blue = np.array([180,255,255])

        mask = cv2.inRange(hsv,lower_blue, upper_blue)

        result = cv2.bitwise_and(frame,frame,mask = mask)

        cv2.imshow('result',result)

        #find center
        cnts=cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[-2]

        center=None

        if len(cnts)>0:
            c=max(cnts, key=cv2.contourArea)
            ((x,y),radius)=cv2.minEnclosingCircle(c)
            M=cv2.moments(c)
            center=(int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))

            if radius>10:
                #cv2.circle(frame, (int(x),int(y)), int(radius), 2)
                cv2.circle(frame, center,5,(0,0,255),-1)



        # color detection limits
        lB = 5
        lG = 50
        lR = 50
        hB = 15
        hG = 255
        hR = 255
        lowerLimits = np.array([lB, lG, lR])
        upperLimits = np.array([hB, hG, hR])

        # Our operations on the frame come here
        thresholded = cv2.inRange(frame, lowerLimits, upperLimits)
        outimage = cv2.bitwise_and(frame, frame, mask = thresholded)


        cv2.imshow('original', frame)

        # Display the resulting frame
        cv2.imshow('processed',outimage)




        # Quit the program when Q is pressed
        if cv2.waitKey(1) & 0xFF == ord('q'):
                break

# When everything done, release the capture
print 'closing program'
cap.release()
cv2.destroyAllWindows()

1 个答案:

答案 0 :(得分:0)

如果您正在尝试按照我的想法行事,您可以使用以下方式轻松完成此操作:

N = 256 / a

image / = N

image * = N

在哪里' a'是你想在新图像中看到的颜色数量,我认为你需要导入numpy才能实现。我认为这可以起作用,因为图像矩阵中的颜色数字被舍入到一个' a'盒子,在你的情况下为3,然后当你用相同的数字计时时缩小到真正的颜色。

对你来说可能为时已晚,但希望这有助于某人。

编辑:使用灰度时只会提供3种颜色,它会在彩色图像上有所不同