opencv 사람 수 인식 코드

2022.05.15 11:17 1,781 조회

opencv로 사람을 인식해서 사각형을 그리는 방법까지는 구현했는데, 이 때 사람 수를 구하는 코드를 짜는 방법을 모르겠습니다ㅠㅜ

어떻게 해야 할까요..??


밑에는 영상으로 사람 인식하는 코드입니다


# import the necessary packages

import numpy as np

import cv2

 

# initialize the HOG descriptor/person detector

hog = cv2.HOGDescriptor()

hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())


cv2.startWindowThread()


# open webcam video stream

cap = cv2.VideoCapture(0)


# the output will be written to output.avi

out = cv2.VideoWriter(

  'output.avi',

  cv2.VideoWriter_fourcc(*'MJPG'),

  15.,

  (640,480))


while(True):

  # Capture frame-by-frame

  ret, frame = cap.read()


  # resizing for faster detection

  frame = cv2.resize(frame, (640, 480))

  # using a greyscale picture, also for faster detection

  gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)


  # detect people in the image

  # returns the bounding boxes for the detected objects

  boxes, weights = hog.detectMultiScale(frame, winStride=(8,8) )


  boxes = np.array([[x, y, x + w, y + h] for (x, y, w, h) in boxes])


  for (xA, yA, xB, yB) in boxes:

    # display the detected boxes in the colour picture

    cv2.rectangle(frame, (xA, yA), (xB, yB),

             (0, 255, 0), 2)

   

  # Write the output video 

  out.write(frame.astype('uint8'))

  # Display the resulting frame

  cv2.imshow('frame',frame)

  if cv2.waitKey(1) & 0xFF == ord('q'):

    break


# When everything done, release the capture

cap.release()

# and release the output

out.release()

# finally, close the window

cv2.destroyAllWindows()

cv2.waitKey(1)

로그인이 필요합니다
0 / 1000
jihyeheo
2022.05.15 19:31

안녕하세요! 데이크루 2기 포스팀입니다! 포스팀은 opencv에 대하여 공부를 진행하고 있는 스터디그룹인데 마침 opencv에 대하여 질문을 올려주셔서 관련 내용으로 코드를 구현해보았습니다. 

제가 생각했을 땐 사람을 인식하여 bounding box를 그리는 것은 bounding box의 개수가 사람의 수와 동일하다고 생각을 하고 코드를 구현해보았습니다. 기기기주님이 올려주신 코드의 중간 부분에 while문 안에 display the detected boxes 요 부분을 다음과 같이 수정했습니다.
 i = 0
    for xA, yA, xB, yB in boxes:
        # display the detected boxes in the colour picture
        cv2.rectangle(frame, (xA, yA), (xB, yB), (0, 255, 0), 2)
        i += 1
    
    cv2.putText(frame,str(i),(50,100),cv2.FONT_HERSHEY_SIMPLEX,1,(255,0,0),2)

좋은 답변이 되었을지 모르겠네요 :) 혹시 또 궁금한 점 있으면 얘기해주세요!

jihyeheo
2022.05.15 19:31

cv2.putText() 함수는 포스팀 게시글 2장 2-5에 관련 인자와 함께 나와있습니다.  

https://dacon.io/codeshare/4837 

참고해주세요 :)