1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
| import dlib import cv2 import imutils import shutil import os import time
name=input("請輸入英文檔案名稱 :") num=input("請輸入預定張數 :") enter=int(num)+1
os.mkdir(str(name)) print('新建【'+str(name)+'】資料夾')
cap = cv2.VideoCapture(0)
sz = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
fps = 30
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
vout = cv2.VideoWriter() vout.open('output.mp4', fourcc, fps, sz, True)
cnt = 0 while cnt < enter: _, frame = cap.read() cv2.putText(frame, str(cnt), (10, 20), cv2.FONT_HERSHEY_PLAIN, 0.8, (0, 255, 0), 1, cv2.LINE_AA) vout.write(frame) cnt += 1
cv2.imshow('vidio', frame) cv2.waitKey(30)
vout.release() cap.release()
cv2.destroyAllWindows()
print("正在裁切影片,形成圖片中...") vc=cv2.VideoCapture("output.mp4") Caimg=0 c=1 if vc.isOpened(): rval,frame=vc.read() else: rval=False while rval: rval,frame=vc.read() cv2.imwrite(str(name)+str(c)+'.jpg',frame) c=c+1 vc.release()
print("圖片形成完成")
os.remove(str(name)+str(enter)+'.jpg')
print("頭像圖片裁切中...")
sum=0 de=0 count=1 while count <= int(str(num)): print (str(name).format(count)+str(count)+".jpg"+" | 完成度 "+'{:.1%}'.format(count/int(str(num))), end="\r") img1 = cv2.imread(str(name)+str(count)+'.jpg')
detector = dlib.get_frontal_face_detector()
face_rects = detector(img1, 1) if len(face_rects) == 0 : print(' | 偵測不到人臉,刪除 '+str(name)+str(count)+'.jpg 的圖檔 | ') de+=1 os.remove(str(name)+str(count)+'.jpg') count+=1 else : for i, d in enumerate(face_rects): x1 = d.left() y1 = d.top() x2 = d.right() y2 = d.bottom() x = x1 y = y1
w = x2 h = y2 img2 = img1[y:h, x:w] img2 = imutils.resize(img2, width=360) cv2.imwrite(str(name)+str(count)+'.jpg', img2) shutil.move(str(name)+str(count)+'.jpg',str(name)) sum+=1 count+=1 print("\n頭像圖片裁切完成")
shutil.move(str(name),'images')
print("相片已刪除 "+str(de)+ "張") print("相片實際輸出為 "+str(sum)+"張")
|