基于opencv-python的人脸识别和鸟图识别
opencv-python图像识别中的人脸识别和鸟图识别
·
目录
一、人脸识别:
即使是地铁挤压的人脸,也是有尊严的,值得被检测,经过 OpenCV 的努力,成功检测:
- 左图是正常被识别的人脸
- 中图由于挤地铁人脸已不可识别
- 右图OpenCV单应性变换后,拯救了被miss的人脸
实现代码如下:
import cv2
import numpy as np
def correct_rust_face():
img_src = cv2.imread('rust_face_src.jpeg')
pts_src = np.array([[0, 0], [0, 1078], [570, 0], [570, 1078]])
img_dst = cv2.imread('rust_face_dest.jpeg')
pts_dst = np.array([[63, 285], [84, 820], [378, 224], [427, 689]])
dw, dh = img_src.shape[1], img_src.shape[0]
h, status = cv2.findHomography(pts_dst, pts_src)
img_out = cv2.warpPerspective(img_dst, h, (dw, dh))
return img_out
def face_detect(input_image):
[x, y, w, h] = [0, 0, 0, 0]
# TODO(You): 实现人脸识别
h, w = input_image.shape[:2]
gray = cv2.cvtColor(input_image, cv2.COLOR_BGR2GRAY)
gray = cv2.equalizeHist(gray)
min_size = (w // 10, h // 10)
face_cascade = cv2.CascadeClassifier(
"data_haarcascades_haarcascade_frontalface_alt.xml")
face_rects = face_cascade.detectMultiScale(gray, 1.05, 2, cv2.CASCADE_SCALE_IMAGE, min_size)
if len(face_rects) > 0:
for face_rect in face_rects:
x, y, w, h = face_rect
cv2.rectangle(input_image, (x, y),
(x + w, y + h), [255, 255, 0], 2)
if __name__ == '__main__':
[x, y, w, h] = [0, 0, 0, 0]
rust_face_src = cv2.imread('rust_face_src.jpeg')
face_detect(rust_face_src)
rust_face_dest = cv2.imread('rust_face_dest.jpeg')
face_detect(rust_face_dest)
rust_face_dest_correct = correct_rust_face()
face_detect(rust_face_dest_correct)
images = np.concatenate(
(rust_face_src[0: 1070, 0:542, 0:3], rust_face_dest, rust_face_dest_correct[0: 1070, 0:542, 0:3]), axis=1)
cv2.imshow('rust_face_detect', images)
cv2.waitKey(0)
cv2.destroyAllWindows()
说明:""data_haarcascades_haarcascade_frontalface_alt.xml""文件可以从OpenCV 官方仓库里人脸分类器模型去下载。
二、鸟图识别
使用基本的OpenCV轮廓检测识别出野外拍摄照片里的鸟:
基本架构代码如下:
mport cv2
if __name__ == '__main__':
img = cv2.imread('bird.jpeg', -1)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, img_binary = cv2.threshold(
img_gray, 127, 255, cv2.THRESH_BINARY)
ret, bin_img = cv2.threshold(
img_binary, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
# findCountours 函数在版本4之后返回参数只有2个
if (int(cv2.__version__[0]) > 3):
contours, hierarchy = cv2.findContours(
bin_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
else:
img2, contours, hierarchy = cv2.findContours(
bin_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# TODO(You): 请在此实现代码
sorted_contours = sorted(contours, key=cv2.contourArea, reverse=False)
max_contour = sorted_contours[-2]
max_contour_area = cv2.contourArea(max_contour)
bird_contours = filter(lambda c: abs(cv2.contourArea(c)-max_contour_area) < 1000, sorted_contours)
for c in bird_contours:
x, y, w, h = cv2.boundingRect(c)
cv2.rectangle(img, (x-10, y-100),
(x+w+10, y+h+10), (0, 255, 0), 2)
cv2.drawContours(img, c, -1, (0, 0, 255), 3)
cv2.imwrite('birds_detect.jpeg', img)
cv2.imshow("birds", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
更多推荐
所有评论(0)