电子说
案例实战
1、简易调色板
def ColorPalette():
# 简易调色板
def callback(value):
print(value)
# trackbar控件
cv2.namedWindow("trackbar",cv2.WINDOW_NORMAL)
cv2.resizeWindow("trackbar",640,480)
cv2.createTrackbar("R","trackbar",0,255,callback)
cv2.createTrackbar("G","trackbar",0,255,callback)
cv2.createTrackbar("B","trackbar",0,255,callback)
bg = np.zeros((480,640,3),np.uint8)
while True:
r = cv2.getTrackbarPos("R","trackbar")
g = cv2.getTrackbarPos("G", "trackbar")
b = cv2.getTrackbarPos("B", "trackbar")
bg[:] = [b,g,r]
cv2.imshow("trackbar",bg)
key = cv2.waitKey(20)
if key == 27:
break
cv2.destroyAllWindows()
# ColorPalette()
2、创建画布,按下指定键画指定图案
def CaptureShape(img):
# 创建画布,按下指定键画指定图案
cur_shape = 0
# 初始坐标
start_pos = (0,0)
def mouse_callback(event,x,y,flags,userdata):
nonlocal start_pos,cur_shape
# 鼠标按下
if event == cv2.EVENT_LBUTTONDOWN:
start_pos = (x,y)
# 鼠标松开
elif event == cv2.EVENT_LBUTTONUP:
if cur_shape == 0:
cv2.line(img,start_pos,(x,y),(0,255,255),2)
elif cur_shape == 1:
cv2.rectangle(img,start_pos,(x,y),(255,0,255),2)
elif cur_shape==2:
a = (x-start_pos[0])
b = (y-start_pos[1])
r = int((a**2+b**2)**0.5)
cv2.circle(img,start_pos,r,(255,255,0),2)
else:
print("not support")
cv2.namedWindow('draw',cv2.WINDOW_NORMAL)
cv2.setMouseCallback('draw',mouse_callback)
while True:
# 按下l键画直线,按下r键画矩形,按下c键画圆
cv2.imshow('draw',img)
key = cv2.waitKey(1)
if key == 27:
break
elif key == ord("l"):
cur_shape = 0
elif key == ord("r"):
cur_shape =1
elif key == ord("c"):
cur_shape =2
cv2.destroyAllWindows()
# img = np.zeros([500,500,3],np.uint8)
# CaptureShape(img)
3、人脸检测
def FaceDetect():
# 人脸检测
face_detector = cv2.CascadeClassifier("./haarcascade_frontalface_alt.xml")
while True:
cap = cv2.VideoCapture(0)
ret,frame = cap.read()
gray = cv2.cvtColor(frame,code=cv2.COLOR_BGR2GRAY)
face = face_detector.detectMultiScale(gray)
for x,y,w,h in face:
cv2.circle(frame,(x+w//2,y+h//2),w//2,(0,255,255),2)
cv2.imshow("img",frame)
key = cv2.waitKey(20)
if key == 27:
break
cap.release()
cv2.destroyAllWindows()
全部0条评论
快来发表一下你的评论吧 !