图片读取
import cv2 as cv
#读取图片
img=cv.imread("yu.jpg")
#显示图片
img=cv.imshow('read_img',img)
#等待
cv.waitKey(0)
#释放内存
cv.destroyAllWindows()
灰度转换
import cv2 as cv
#读取图片
img=cv.imread("yu.jpg")
#灰度转换
gray_img=cv.cvtColor(img,cv.COLOR_BGR2GRAY)
#显示灰度
cv.imshow('gray',gray_img)
#显示图片
img=cv.imshow('read_img',img)
#等待
cv.waitKey(0)
#释放内存
cv.destroyAllWindows()
修改尺寸
import cv2 as cv
img=cv.imread('yu.jpg')
#修改尺寸
cv.imshow('yu',img)
#修改前
resize_img=cv.resize(img,dsize=(200,200))
cv.imshow('yu1',resize_img)
#修改后
while True:
if ord('q')==cv.waitKey(0):
break
cv.destoryAllWindows()
绘制矩形与圆形
import cv2 as cv
img=cv.imread('yu.jpg')
#坐标
x,y,w,h=100,100,100,100
#绘制矩形
cv.rectangle(img,(x,y,x+w,y+h),color=(0,0,255),thickness=1)
#绘制圆形
cv.circle(img,center=(x+w,y+h),radius=100,color=(255,0,0),thickness=2)
#显示
cv.imshow('lan',img)
#修改后
while True:
if ord('q')==cv.waitKey(0):
break
cv.destoryAllWindows()
人脸检测(多人和单人都可以)
import cv2 as cv
def face_detect_demo():
gray=cv.cvtColor(img,cv.COLOR_BGR2GRAY)
face_detect=cv.CascadeClassifier('C:/Users/whuim/PycharmProjects/pythonProject1/opencv/haarcascade_frontalface_alt.xml')
face=face_detect.detectMultiScale(gray)
for x,y,w,h in face:
cv.rectangle(img,(x,y),(x+w,y+h),color=(0,0,225),thickness=2)
cv.imshow('result',img)
img=cv.imread('img_1.png')
face_detect_demo()
while True:
if ord('q')==cv.waitKey(0):
break
cv.destoryAllWindows()
视频人脸识别
import cv2 as cv
def face_detect_demo(img):
gray=cv.cvtColor(img,cv.COLOR_BGR2GRAY)
face_detect=cv.CascadeClassifier('C:/Users/whuim/PycharmProjects/pythonProject1/opencv/haarcascade_frontalface_alt.xml')
face=face_detect.detectMultiScale(gray)
for x,y,w,h in face:
cv.rectangle(img,(x,y),(x+w,y+h),color=(0,0,225),thickness=2)
cv.imshow('result',img)
# cv.imshow('re',gray)
# img=cv.imread('yu.jpg')
# face_detect_demo()
#读取摄像头
cap=cv.VideoCapture('1.mp4')
#循环
while True:
flag,frame=cap.read()
if not flag:
break
face_detect_demo(frame)
if ord('q')==cv.waitKey(0):
break
cv.destoryAllWindows()
#释放摄像头
cap.relrese()