将面部的范围识别出来后,可以对识别出来的部分进行抓取。抓取一张图片中
的部分图形是通过 pillow 包中的 crop 方法来实现的
我们首先学习用 pillow 包来读取图片文件,语法为:
例如,打开 test.jpg 图片文件,然后保存至 img 变量:
接着我们用 crop 方法抓取图片的指定范围,语法为:
例如,抓取( 50,50 )到( 200,200 )的图片并保存在 img2 变量:
不同图片所抓取下来的面部大小可能不一致,为了方便图形对比,可以将图片
调整为固定大小 。 pillow 包中的 resize 方法可实现对图片尺寸的重新设定:
抓取图片中的面部区域并保存
先用 OpenCV 取得面部区域 , 再用 pillow 包中的 crop 方法抓取面部区域并保存 。
import cv2 from PIL import Image casc_path = "E:\haarcascade_frontalface_default.xml" faceCascade = cv2.CascadeClassifier(casc_path) imagename = "F:\pythonBase\pythonex\ch10\media\person1.jpg" image = cv2.imread(imagename) faces = faceCascade.detectMultiScale(image, scaleFactor=1.1, minNeighbors=5, minSize=(30,30), flags = cv2.CASCADE_SCALE_IMAGE) count = 1 for (x,y,w,h) in faces: cv2.rectangle(image, (x,y), (x+w,y+h), (128,255,0), 2) filename = "E:\" + str(count)+ ".jpg" image1 = Image.open(imagename) image2 = image1.crop((x, y, x+w, y+h)) image3 = image2.resize((200, 200), Image.ANTIALIAS) image3.save(filename) count += 1 cv2.namedWindow("facedetect") cv2.imshow("facedetect", image) cv2.waitKey(0) cv2.destroyWindow("facedetect")
import cv2 from PIL import Image casc_path = "E:\haarcascade_frontalface_default.xml" faceCascade = cv2.CascadeClassifier(casc_path) imagename = "F:\pythonBase\pythonex\ch10\media\person3.jpg" image = cv2.imread(imagename) faces = faceCascade.detectMultiScale(image, scaleFactor=1.1, minNeighbors=5, minSize=(30,30), flags = cv2.CASCADE_SCALE_IMAGE) count = 1 for (x,y,w,h) in faces: cv2.rectangle(image, (x,y), (x+w,y+h), (128,255,0), 2) filename = "E:\aa\" + str(count)+ ".jpg" image1 = Image.open(imagename) image2 = image1.crop((x, y, x+w, y+h)) image3 = image2.resize((200, 200), Image.ANTIALIAS) image3.save(filename) count += 1 cv2.namedWindow("facedetect") cv2.imshow("facedetect", image) cv2.waitKey(0) cv2.destroyWindow("facedetect")
import cv2 from PIL import Image casc_path = "E:\haarcascade_frontalface_default.xml" faceCascade = cv2.CascadeClassifier(casc_path) imagename = "F:\pythonBase\pythonex\ch10\media\person8.jpg" image = cv2.imread(imagename) faces = faceCascade.detectMultiScale(image, scaleFactor=1.1, minNeighbors=5, minSize=(30,30), flags = cv2.CASCADE_SCALE_IMAGE) count = 1 for (x,y,w,h) in faces: cv2.rectangle(image, (x,y), (x+w,y+h), (128,255,0), 2) filename = "E:\aa\bb\" + str(count)+ ".jpg" image1 = Image.open(imagename) image2 = image1.crop((x, y, x+w, y+h)) image3 = image2.resize((200, 200), Image.ANTIALIAS) image3.save(filename) count += 1 cv2.namedWindow("facedetect") cv2.imshow("facedetect", image) cv2.waitKey(0) cv2.destroyWindow("facedetect")