본문 바로가기
파이썬

파이썬 Python + OpenCV : cv2.imwrite

by º기록 2020. 12. 28.
반응형

얼굴을 감지하고 얼굴이있는 영역을 별도의 파일에 기록하려고합니다. 내가 어떻게 해? "얼굴"을 사용해야한다고 생각합니다 (코드에서이 변수를 볼 수 있습니다). 하지만 어떻게?

from ffnet import mlgraph, ffnet, tmlgraph, imlgraph
import pylab
import sys
import cv,cv2
import numpy
cascade = cv.Load('C:\opencv\data\haarcascades\haarcascade_frontalface_alt.xml')


def detect(image):
 bitmap = cv.fromarray(image)
 faces = cv.HaarDetectObjects(bitmap, cascade, cv.CreateMemStorage(0))
 if faces:
  for (x,y,w,h),n in faces:  
   cv2.rectangle(image,(x,y),(x+w,y+h),(255,255,255),3)
 return image

if __name__ == "__main__":
    cam = cv2.VideoCapture(0)
    while 1:
        _,frame =cam.read()
        frame = numpy.asarray(detect(frame))
        cv2.imshow("features", frame)
        if cv2.waitKey(1) == 0x1b: # ESC
            print 'ESC pressed. Exiting ...'
            break

 

해결 방법

 

다음 코드는 이미지에서 얼굴을 추출하고 디스크에 얼굴을 저장해야합니다.

def detect(image):
    image_faces = []
    bitmap = cv.fromarray(image)
    faces = cv.HaarDetectObjects(bitmap, cascade, cv.CreateMemStorage(0))
    if faces:
        for (x,y,w,h),n in faces:
            image_faces.append(image[y:(y+h), x:(x+w)])
            #cv2.rectangle(image,(x,y),(x+w,y+h),(255,255,255),3)
    return image_faces

if __name__ == "__main__":
    cam = cv2.VideoCapture(0)
    while 1:
        _,frame =cam.read()
        image_faces = []
        image_faces = detect(frame)
        for i, face in enumerate(image_faces):
            cv2.imwrite("face-" + str(i) + ".jpg", face)

        #cv2.imshow("features", frame)
        if cv2.waitKey(1) == 0x1b: # ESC
            print 'ESC pressed. Exiting ...'
            break

 

참조 페이지 https://stackoverflow.com/questions/20425724

 

 

반응형

댓글