곰퓨타의 SW 이야기

[python] openCV로 txt file 활용하여 bounding box, box labeling 하기 본문

Project/python 활용(ex.openCV)

[python] openCV로 txt file 활용하여 bounding box, box labeling 하기

곰퓨타 2021. 4. 21. 11:22

 

참고한 사이트는 다음과 같다.
opencv-python.readthedocs.io/en/latest/doc/01.imageStart/imageStart.html

 

이미지 다루기 — gramman 0.1 documentation

cv2.imread() 함수를 이용하여 이미지 파일을 읽습니다. 이미지 파일의 경로는 절대/상대경로가 가능합니다. 이미지 읽기의 flag는 3가지가 있습니다. Note 3개의 flag대신에 1, 0, -1을 사용해도 됩니다.

opencv-python.readthedocs.io

 

 

MOT-neural-solver를 실행하였을 때,

bounding box 및 image를 input으로 주면, image 에 대한 bounding box 좌표 및 tracktor, label 관련 결과를 얻어낼 수 있다.

 

수행한 결과를 시각화 하기 위해 다음과 같은 코드를 만들었다.

이는 txt 파일에 있는 것을 numpy 배열로 입력 받고, 입력 받은 배열에 대해 bounding box(rectangle) 및 label을 시각화하기 위해 만들었다.

 

import cv2
import numpy as np

annot = np.loadtxt('path_txt_file',delimiter=',',skiprows=0,dtype= float)
print(annot.shape)

np.random.seed(0)
bbox_color = [list(np.random.random(size=3) * 256) for _ in range(3000)]
frame_num = 1
count = 0

while (True):
    # frame 별로 capture 한다
    temp = annot[count][0]
    
    # 사람이 detect되지 않은 경우 
    if frame_num != int(temp) :
        img = cv2.imread('path_input_image_folder/%06d.jpg' %frame_num)
        cv2.imwrite('path_output_image_folder/%06d.jpg' % frame_num, img)
        frame_num += 1
        continue

	# 사람이 detect 된 경우
    img = cv2.imread('path_input_image_folder/%06d.jpg' % frame_num)
	
    # 해당 frame에서 detect된 사람 만큼 bounding box 및 text 삽입 
    while temp == annot[count][0]:
        img = cv2.rectangle(img, (int(annot[count][2]),int(annot[count][3])), (int(annot[count][2] + annot[count][4]), int(annot[count][3] + annot[count][5])), bbox_color[int(annot[count][1])], 3)
        cv2.putText(img, str(annot[count][1]),  (int(annot[count][2] + annot[count][4]), int(annot[count][3] + annot[count][5])), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 0), 1)
        count += 1
        if count > len(annot) - 1:
            break

    # cv2.imshow('img',img)
    # cv2.waitKey(0)
    cv2.imwrite('path_output_image_folder/%06d.jpg'%frame_num,img)
    frame_num += 1
    if count > len(annot)-1 :
        print("finish drawing!!")
        break


# 메모리를 해제시켜준다.
cv2.destroyAllWindows()



# 아래는 다음글에서 다시 정리하겠지만, 파이썬에서 terminal에 있는 명령을 수행하기 위한 코드이다.
# image -> video로 만들기 위함 
import os
os.system("ffmpeg -f image2 -r 28 -i /path_output_image_folder/%06d.jpg -vcodec"
          " mpeg4 -y /path_output_video_file.mp4")

 

이를 수행하면 다음과 같은 결과가 나온다. 이는 동영상 중 일부이다.

 

 

 

 

Comments