人脸检测
import cv2 as cv
def face_detect_demo():
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
face_detect = cv.CascadeClassifier('E:/project/renlian/shibie/haarcascade_frontalface_default.xml')
faces = face_detect.detectMultiScale(gray)
for x,y,w,h in faces:
cv.rectangle(img,(x,y),(x+w,y+h),color=(0,255,0),thickness=2)
cv.imshow('result',img)
img = cv.imread('mei.jpg')
face_detect_demo()
cv.waitKey(0)
cv.destroyAllWindows()
修改图片尺寸
import cv2 as cv
img = cv.imread('kuli.jpg')
resize_img = cv.resize(img,dsize=(400,360))
print(resize_img.shape)
cv.imshow('resize_img',resize_img)
while True:
if ord('q') == cv.waitKey(0):
break
cv.destroyAllWindows()
加载图片
首先确保机器上是否安装python环境,默认为已经安装的机器。
接下来我们安装opencv的库,
pip install opencv-python
读取图片使用imshow()来显示图片,
import cv2 as cv
img = cv.imread('wenqi.jpg')
cv.imshow('input image!',img)
cv.waitKey(0)
cv.destroyAllWinows()
图片灰化
为什么将图片进行灰化?
灰度色彩空间是通过去除彩色信息来将其转换为灰阶,灰度色彩空间对中间处理特别有效,如人脸识别。
灰度转化的作用是:转换为灰度的图片的计算强度得以降低。
import cv2 as cv
img = cv.imread('kuli.jpg')
cv.imshow('my image!',img)
gray_img = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
cv.imshow('gray_image',gray_img)
cv.imwrite('gray_kuli.jpg',gray_img)
cv.waitKey(0)
cv.destroyAllWindows()
检测多张人脸
import cv2 as cv
def face_detect_demo():
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
face_detect = cv.CascadeClassifier('E:/project/renlian/shibie/haarcascade_frontalface_default.xml')
faces = face_detect.detectMultiScale(gray)
for x,y,w,h in faces:
cv.rectangle(img,(x,y),(x+w,y+h),color=(0,255,0),thickness=2)
cv.circle(img,center=(x+w//2,y+h//2),radius=w//2,color=(0,0,255),thickness=2)
cv.imshow('result',img)
img = cv.imread('lao.jpg')
face_detect_demo()
cv.waitKey(0)
cv.destroyAllWindows()
画图
import cv2 as cv
img = cv.imread('kuli.jpg')
x,y,w,h = 150,150,200,200
cv.rectangle(img,(x,y,x+w,y+h),color=(0,0,255),thickness=2)
x,y,r = 200,200,100
cv.circle(img,center=(x,y),radius=r,color=(0,0,255),thickness=2)
cv.imshow('result_img',img)
cv.waitKey(0)
cv.destroyAllWindows()
视频中的人脸识别
import cv2 as cv
def face_detect_demo(img):
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
face_detect = cv.CascadeClassifier('E:/project/renlian/shibie/haarcascade_frontalface_default.xml')
faces = face_detect.detectMultiScale(gray)
for x,y,w,h in faces:
cv.rectangle(img,(x,y),(x+w,y+h),color=(0,0,255),thickness=2)
cv.circle(img,center=(x+w//2,y+h//2),radius=(w//2),color=(0,255,0),thickness=2)
cv.imshow('result',img)
cap = cv.VideoCapture('meinv.mp4')
while True:
flag,frame = cap.read()
print('flag:',flag,'frame.shape:',frame.shape)
if not flag:
break
face_detect_demo(frame)
if ord('q') == cv.waitKey(10):
break
cv.destroyAllWindows()
cap.release()
|