OpenCV入门之OpenCV的基本操作实战代码

电子说

1.3w人已加入

描述

案例实战

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()
打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分