opencv基础入门
安装opencv
pip install opencv-python
读取图片
import cv2 as cv img = cv.imread("images/luo.jpg") cv.imshow("罗翔",img) # 等待 cv.waitKey(0) cv.destroyAllWindows()
改变灰度
import cv2 as cv img = cv.imread("images/luo.jpg") # 灰度处理 hd_img = cv.cvtColor(img,cv.COLOR_BGR2GRAY) cv.imshow("罗翔",hd_img) # 等待 cv.waitKey(0) cv.destroyAllWindows()
修改图片尺寸
import cv2 as cv img = cv.imread("images/luo.jpg") # 修改尺寸 resize_img = cv.resize(img,dsize=(200,200)) # 显示原图 cv.imshow("luo",img) # 显示改变 cv.imshow("luo2",resize_img) # 打印大小 print("原图",img.shape) print("原图",resize_img.shape) # 等待 cv.waitKey(0) cv.destroyAllWindows()
对图片人脸识别
import cv2 as cv def face_detect_demo(): hd = cv.cvtColor(img,cv.COLOR_BGR2GRAY) # 引入OpenCV源码里分类器 face_detect = cv.CascadeClassifier("D:/opencv-4.5.5/data/haarcascades/haarcascade_frontalface_alt2.xml") face = face_detect.detectMultiScale(hd,1.2,5,0,(100,100),(300,300)) for x,y,w,h in face: cv.rectangle(img,(x,y),(x+w,y+h),color=(0,0,255),thickness=2) cv.imshow("result",img) if __name__ == "__main__": img = cv.imread("images/luo.jpg") # 调用人脸检测函数 face_detect_demo() # 等待 cv.waitKey(0) cv.destroyAllWindows()