def change_B(x):
global color_thred
color_thred[0] = x
def change_G(x):
global color_thred
color_thred[1] = x
def change_R(x):
global color_thred
color_thred[2] = x
# 通过颜色范围获取obj
def catchobj(frame, color_thred=[100, 50, 50]):
condition = (frame[:, :, 0] > color_thred[0]) & (frame[:, :, 1] < color_thred[1]) & (frame[:, :, 2] < color_thred[2])
# obj = np.where(condition.reshape(*condition.shape, -1), frame, 0).astype(np.uint8)
#根据值域生成掩码
obj = np.where(condition.reshape(*condition.shape, -1), 255, 0).astype(np.uint8)
mask = obj.reshape(obj.shape[0], -1)
#cv2.imshow('mask', mask)
#cv2.waitKey(0)
# return obj
return mask
cap = cv2.VideoCapture('IMG_9739.MP4')
# print(cap.isOpened())
cv2.namedWindow('original frame')
cv2.namedWindow('catch object')
cv2.createTrackbar('B', 'catch object', color_thred[0], 255,change_B) # 控件名,窗口名,最小最大值,回调函数
cv2.createTrackbar('G', 'catch object', color_thred[1], 255, change_G)
cv2.createTrackbar('R', 'catch object', color_thred[2], 255, change_R)
while True:
ret, frame = cap.read()
if not ret:
break
# obj = catchobj(frame, color_thred)
mask = catchobj(frame, color_thred)
res = cv2.bitwise_and(frame, frame, mask=mask)
# cv2.imshow('original frame', frame)
h,w,_=res.shape
res=cv2.resize(res,(int(h*0.5),int(w*0.5)))
cv2.imshow('catch object', res)
# cv2.imwrite('datas\video_imgs\1.jpg',frame) #保存一幅图片,看看以下颜色是怎么样的
cv2.waitKey(1000//10)
cap.release()
cv2.destroyAllWindows()