對當前文件夾下所有圖片,識別圖片中的人臉,並按比例切割後保存

感謝前輩的資料,這裏做搬運工整合了下

對當前文件夾下所有圖片,識別圖片中的人臉,並按比例切割後保存

——————————————————————————

#coding=utf-8
# 2020 03 11 zhanghu 
import requests,cv2
import re
import os
import bs4

#安裝bs4 pip3 install Beautifulsoup4 

def cuttingImage(sourceimg="1.jpg",exportImg="1_new.jpg"):
    #.讀取圖片
    curpath = os.path.dirname(os.path.realpath(__file__))   
    filename = os.path.join(curpath, sourceimg)    
    image = cv2.cv2.imread(filename)
    #豎屏照片 480*640 960*1280
    #print(image.shape)
    new_w=480
    new_h=int((image.shape[0])*new_w/(image.shape[1]))
    image=cv2.cv2.resize(image,(new_w,new_h))

    #.加載人臉模型 級聯分類器
    facemodelPath= os.path.join(curpath, "facemodel.xml") 
    face_moel =  cv2.cv2.CascadeClassifier(facemodelPath)

    #.對圖片進行灰度處理
    gray =  cv2.cv2.cvtColor(image, cv2.cv2.COLOR_RGB2GRAY)

    #.檢查人臉
    faces = face_moel.detectMultiScale(gray)  
   

    #.標記人臉(橢圓形、三角形、矩形)
    for (x,y,w,h) in faces:
        print("x,y,w,h",x,y,w,h)
        c_x=int(x+w/2)
        c_y=int(y+h/2)
        n_w=w*3
        n_h=int(n_w*4/3) 
        n_x1= 0  if  c_x-int(n_w/2)<0  else  c_x-int(n_w/2)
        n_y1= 0  if  c_y-int(n_h/2)<0  else  c_y-int(n_h/2)
        n_x2= new_w  if  (n_x1+n_w)>new_w  else  (n_x1+n_w)
        n_y2= new_h  if  (n_y1+n_h)>new_h  else  (n_y1+n_h)
        print("n_w,n_h,n_x1,n_y1,n_x2,n_y2",n_w,n_h,n_x1,n_y1,n_x2,n_y2)
        #.原始圖片 2.左上角座標 3.右下角座標 4.顏色值 5.線寬   
        #cv2.cv2.rectangle(image,(x,y),(x+w,y+h),(0,255,0),2)
        #。裁剪線
        #cv2.cv2.rectangle(image,(n_x1,n_y1),(n_x2,n_y2),(0,255,0),2)
        #裁剪圖片
        image=image[n_y1:n_y2,n_x1:n_x2 ]
        #調整圖片分辨率
        new_w=480
        new_h=int((image.shape[0])*new_w/(image.shape[1]))
        image=cv2.cv2.resize(image,(new_w,new_h))

        #save image    
        saveImgPath=os.path.join(curpath, exportImg)
        if os.path.isfile(saveImgPath):
            os.remove(saveImgPath)    
        cv2.cv2.imwrite(saveImgPath,image)

        #.顯示圖片
        #cv2.cv2.imshow('face',image)

        #.暫停窗口
        #cv2.cv2.waitKey(0)
        #.銷燬窗口
        #cv2.cv2.destroyAllWindows()

#----------------------------------------------------------------------------------------------
#-------------------------------------------main-----------------------------------------------
#----------------------------------------------------------------------------------------------
if __name__ == '__main__':  
    curpath = os.path.dirname(os.path.realpath(__file__))   
    dirs=os.listdir(curpath)
    for file in dirs:
        if file.find(".jpg")>3 and -1==file.find("_new.jpg"):
           print("--------------->"+file+".....") 
           s_img= os.path.join(curpath, file)  
           e_img= os.path.join(curpath, file.replace(".jpg","_new.jpg"))   
           cuttingImage(s_img,e_img)
           print("\r\n")
          
           

    print("script complete!")        

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章