Interface編集部
12-3FacePhoto.py
000: import cv2
001: import numpy as np
002:
003: def __main():
004: maxPhotoNum = 100
005:
006: cap = cv2.VideoCapture(0, cv2.CAP_V4L)
007: cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
008: cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
009:
010: if not cap.isOpened(): # ビデオ・キャプチャ可能か判断
011: print(“Not Opened Video Camera”)
012: exit()
013:
014: while True:
015: ret, img = cap.read()
016:
017: if not ret: # キャプチャ画像取得に失敗したら終了
018: print(“Video Capture Err”)
019: break
020:
021: # ここで処理を実行する
022: dst = setResultArea(img)
023: getface(dst)
024: x1, y1, x2, y2 = init(img)
025: img[y1:y2, x1:x2] = dst
026: cv2.rectangle(img,(50, 50), (330, 120),(0, 0, 0), -1)
027: cv2.putText(img=img, text=”{0}/{1}”.format(str(faceCount).zfill(3), maxPhotoNum), org=(80, 100),
028: fontFace=cv2.FONT_HERSHEY_SIMPLEX,
029: fontScale=1.5, color=(255, 255, 255), lineType=cv2.LINE_AA)
030:
031: cv2.imshow(“Final result”, img) # 画面表示
032: if cv2.waitKey(10) > -1:
033: break
034: if faceCount >= maxPhotoNum:
035: break
036:
037: cap.release()
038: cv2.destroyAllWindows()
039:
040: return 0
041:
042: def init(src):
043: h = src.shape[0]
044: w = src.shape[1]
045: x = w / 2
046: y = h / 2
047: rectLength = w * 0.3
048: x1 = int(x – (rectLength / 2))
049: y1 = int(y – (rectLength / 2))
050: x2 = int(x + (rectLength / 2))
051: y2 = int(y + (rectLength / 2))
052:
053: return x1, y1, x2, y2
054:
055: def setResultArea(src):
056: x1, y1, x2, y2 = init(src)
057: dst = src[y1:y2, x1:x2]
058: cv2.rectangle(src, (x1, y1), (x2, y2), (255, 255, 255), 2)
059:
060: return dst
061:
062: def getface(img):
063: global cascade
064: gray = cv2.cvtColor(src=img, code=cv2.COLOR_BGR2GRAY)
065: bodyRect = cascade.detectMultiScale(image=gray, scaleFactor=1.05, minNeighbors=10, flags=None, minSize=(30, 30))
066: for x, y, w, h in bodyRect:
067: face = img[y:y+h, x:x+w]
068: saveImg(face)
069: cv2.rectangle(img=img, pt1=(x, y), pt2=(x + w, y + h), color=(0, 255, 255), thickness=3)
070: return img
071:
072: def saveImg(src):
073: global faceCount
074: dst = setImageSize(src, faceCount)
075: dst = cv2.cvtColor(dst, cv2.COLOR_BGR2GRAY)
076: fileName = “./facesImage/face{0}.jpg”.format(faceCount)
077: cv2.imwrite(fileName, dst)
078: faceCount += 1
079:
080: def setImageSize(src, count):
081: global height
082: global width
083:
084: if count > 0:
085: h = src.shape[0]
086: w = src.shape[1]
087: rate = height / h
088: print(rate)
089: src =cv2.resize(src, (int(w * rate), int(h * rate)))
090: else:
091: height = src.shape[0]
092: width = src.shape[1]
093: return src
094:
095: if __name__ == ‘__main__’:
096: faceCount = 0
097: height = 0
098: width = 0
099: cascade = cv2.CascadeClassifier(‘haarcascade_frontalface_default.xml’)
100: __main()