import cv2
import os
import re
from datetime import datetime
files = os.listdir('.')
img_files = list(filter(lambda x: '.jpg' in x, files))
print(img_files)
#라벨 인덱스 기준
std_val = [
datetime.strptime("2022-08-26 00:00:00", '%Y-%m-%d %H:%M:%S'),
datetime.strptime("2022-08-27 00:00:00", '%Y-%m-%d %H:%M:%S'),
datetime.strptime("2022-08-28 00:00:00", '%Y-%m-%d %H:%M:%S'),
datetime.strptime("2022-08-29 00:00:00", '%Y-%m-%d %H:%M:%S')
]
#파일 리스트 반복
for img_file in img_files:
idx = 0 #인덱스 초기화
#파일 이름에서 날짜, 시간 추출
img_split = img_file.replace(".jpg","").split(" ")
year = img_split[0] #날짜
times = str(img_split[1])
times = re.findall(r'\d+',times)
#날짜 포멧에 맞게 문자열 변수에 저장
dt_str = year+" "+times[0]+":"+times[1]+":"+times[2]
#날자 타입으로 생성
dt_obj = datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S')
#기준값을 비교하면서 기준값 범위에 있으면 idx에 인덱스 번호 저장
for i, std in enumerate(std_val):
if dt_obj <= std:
idx =i
break
#이미지 read
img_org = cv2.imread(img_file)
#이미지 높이, 너비 가져오기
height,width,_ =img_org.shape
#윤곽 그릴 이미지 복제
img_object = img_org.copy()
#바운딩 박스 이미지 복제
img_rectangle = img_org.copy()
#가우시안 블러 적용
imblur = cv2.GaussianBlur(img_object, (0, 0), 1)
#블러 적용 (잡음제거)
imgray = cv2.cvtColor(imblur, cv2.COLOR_BGR2GRAY)
#경계값 찾기
ret, imthres = cv2.threshold(imgray, 150, 255, cv2.THRESH_BINARY_INV)
#윤곽선 찾기
contour, hierarchy = cv2.findContours(imthres, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
#윤곽 그리기
cv2.drawContours(img_object, contour, -1, (0,255,0), 1)
#파일 쓰기 시작
f = open(img_file.replace(".jpg", ".txt"), 'w')
#추출된 윤곽선을 반복하며 해당 윤곽정보 저장 반복
for c in contour:
x, y, w, h = cv2.boundingRect(c)
frame = img_org[y:y + h, x:x + w]
# Make sure contour area is large enough
if (cv2.contourArea(c)) > 200000:
cv2.rectangle(img_rectangle, (x, y), (x + w, y + h), (255, 0, 0), 5)
# print((x, y), (x + w, y + h),)
#YOLO 라벨 형태로 변환
xc = ((x + (x+w))/2)/width
yc = ((y + (y+h))/2)/height
xc2 = w / width
yc2 = h / height
#파일에 형식에 맞게 작성
f.write(str(idx)+' '+str(xc)+" "+str(yc)+" "+str(xc2)+" "+str(yc2)+"\n")
#파일 작성종료
f.close()