AI入门:实现图片人脸识别
source link: https://mp.weixin.qq.com/s?__biz=MzIxMTg4NDg0MA%3D%3D&%3Bmid=2247485433&%3Bidx=1&%3Bsn=26931b9d2ea04cc078c113f47d807cc3
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
AI领域非常广泛,从信息的载体可分为文字、图片、声音、视频等,当我真的想要学习AI的时候,有点无从下手。从什么方向入门,学习什么库?
前几天逛github,发现了一个识别人脸的教程:
https://github.com/vipstone/faceai
看了一个入门还是非常简单的。
安装:
安装包都比较大,可以使用豆瓣源:
-i https://pypi.douban.com/simple
> pip install numpy > pip install opencv-python
备注:dlib 库非难安装
首先,使用 opencv 打开一张图
import cv2
img = cv2 . imread ( " d:/tc/faceai/meinv.jpg " )
cv2 . namedWindow ( ' Image ' )
cv2 . imshow ( ' Image ' , img )
cv2 . waitKey ( 0 )
cv2 . destroyAllWindows ()
人脸识别
要想识别一张图片上的人脸分三步:
-
将彩色图片转换为灰色,转为一维的灰度,降低计算强度。
import cv2
img = cv2 . imread ( ' d:/tc/faceai/meinv.jpg ' )
# 转换灰色
gray = cv2 . cvtColor ( img , cv2 . COLOR_BGR2GRAY )
cv2 . imshow ( " Image " , gray )
cv2 . waitKey ( 0 )
cv2 . destroyAllWindows ()
-
通过矩形画出人脸位置。
import cv2
img = cv2 . imread ( ' d:/tc/faceai/meinv.jpg ' )
gray = cv2 . cvtColor ( img , cv2 . COLOR_BGR2GRAY )
# 绘制矩形
x = y = 10 # 坐标
w = 100 # 矩形大小(宽、高)
color = ( 0 , 0 , 255 ) # 定义绘制颜色
cv2 . rectangle ( img , ( x , y ), ( x + w , y + w ), color , 1 ) # 绘制矩形
cv2 . imshow ( " Image " , img ) # 显示图像
cv2 . waitKey ( 0 )
cv2 . destroyAllWindows () # 释放所有的窗体资源
-
使用训练分类器查找人脸。
这一步的核心是使用 opencv 的人脸训练模型,下载地址:
https://github.com/opencv/opencv/tree/master/data/haarcascades
这里选择 haarcascade_frontalface_default.xml
文件,你可以下载到本地。
import cv2
img = cv2 . imread ( ' d:/tc/faceai/meinv.jpg ' )
gray = cv2 . cvtColor ( img , cv2 . COLOR_BGR2GRAY )
# OpenCV人脸识别分类器
classifier = cv2 . CascadeClassifier ( " d:/tc/faceai/haarcascade_frontalface_default.xml " )
color = ( 0 , 255 , 0 ) # 定义绘制颜色
# 调用识别人脸
faceRect = classifier . detectMultiScale ( gray , scaleFactor = 1.2 , minNeighbors = 3 , minSize = ( 32 , 32 ))
if len ( faceRect ): # 大于0则检测到人脸
for faceRect in faceRect : # 单独框出每一张人脸
x , y , w , h = faceRect
# 框出人脸
cv2 . rectangle ( img , ( x , y ), ( x + h , y + w ), color , 2 )
# 左眼
cv2 . circle ( img , ( x + w // 4 , y + h // 4 + 30 ), min ( w // 8 , h // 8 ),
color )
# 右眼
cv2 . circle ( img , ( x + 3 * w // 4 , y + h // 4 + 30 ), min ( w // 8 , h // 8 ),
color )
# 嘴巴
cv2 . rectangle ( img , ( x + 3 * w // 8 , y + 3 * h // 4 ),
( x + 5 * w // 8 , y + 7 * h // 8 ), color )
cv2 . imshow ( " image " , img ) # 显示图像
c = cv2 . waitKey ( 10 )
cv2 . waitKey ( 0 )
cv2 . destroyAllWindows ()
那么,我们已经识别出美女的五官了。
我们可以使用opencv训练自己的分类器,比如识别页面上的按钮、输入框等,那么是不是就可以通过AI来定位元素了。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK