# -- coding: utf-8 --
import cv2
import numpy as np
import os
from PIL import Image,ImageDraw
def detectFaces(image_name):
img=cv2.imread(image_name)
face_cascade=cv2.CascadeClassifier("D:\\CWFace\\MyFaceDemo\\opencv310\\opencv\\build\\etc\\haarcascades\\haarcascade_frontalface_default.xml")
if img.ndim == 3:
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
else:
gray = img
faces = face_cascade.detectMultiScale(gray,1.2,5)
result=[]
for(x,y,width,height) in faces:
result.append((x,y,x+width,y+height))
return result
def saveFaces(image_name):
faces = detectFaces(image_name)
print len(faces)
count=1
img =cv2.imread(image_name)
#print(img)
file_path = "D:\\CWFace\\python27test\\img"
for (x1,y1,x2,y2) in faces:
file_face=os.path.join(file_path,str(count)+".jpg")
#上、下、左、右扩充
x2 = x2 -1
y2 = y2 -1
dD=x2-x1
x1=x1-dD/3.0
x2=x2+dD/2.2
y1=y1-dD/2.8
y2=y2+dD/2.2
#防止溢出
#x1=max(x1,1)
#x2=min(x2,img.shape[0]-2)
#y1=max(y1,1)
#y2=min(y2,img.shape[1]-2)
#img.colRange(x1,x2).rowRange(y1,y2).clone()
cv2.imwrite(file_face, img[int(y1):int(y2), int(x1):int(x2), :])
#Image.open(image_name).crop((x1,y1,x2,y2)).save(file_face)
count+=1
def drawFaces(image_name):
faces=detectFaces(image_name)
count =1
if faces:
img = Image.open(image_name)
draw_instance = ImageDraw.Draw(img)
for(x1,y1,x2,y2) in faces:
draw_instance.rectangle((x1,y1,x2,y2),outline=(255,0,0))
file_path = "D:\\CWFace\\python27test\\pic"
file_face = os.path.join(file_path, str(count) + ".jpg")
img.save(file_face)
def salt(img,n):
for k in range(n):
i=int(np.random.random() * img.shape[1])
j=int(np.random.random() * img.shape[0])
if img.ndim == 2:
img[j,i] = 255
elif img.ndim ==3:
img[j,i,0]=255
img[j,i,1]=255
img[j,i,2]=255
return img
if __name__ == '__main__':
a=3
dDis=a-1
print dDis
dl=a-dDis/3.0
print dl
saveFaces('9.jpg')
drawFaces('9.jpg')
print('OK')
"""
imge=cv2.imread('6.jpg')
print imge.shape
print imge.shape[0]
print imge.shape[1]
saltImage = salt(imge,500)
cv2.imshow("Src", imge)
cv2.imshow("Salt",saltImage)
cv2.waitKey(0)
drawFaces('6.jpg')
capture = cv2.VideoCapture(0)
#save =cv2.VideoWriter('D:\\CWFace\\python27test\\save.avi',-1,20.0,(640,480))
while True:
ret,frame =capture.read()
if ret == True:
cv2.imshow("capture",frame)
#save.write(frame)
if cv2.waitKey(1)&0xFF==ord('q'):
cv2.imwrite("D:\\CWFace\\python27test\\5.jpg",frame)
print"OK"
break
print __name__
capture.release()
#save.release()
cv2.destroyAllWindows()
"""
python-opencv图像处理基础练习1
最新推荐文章于 2022-11-15 22:50:30 发布