학습한 내용
import os
import json
import cv2
import numpy as np
json_path="./raccoon/anno/raccoon_annotations.coco.json"
with open(json_path,"r") as f:
coco_info=json.load(f)
print(coco_info)
#json 파일 들어있음
# len(coco_info)>0이 아니면 파일 읽기 실패
assert len(coco_info)>0,"파일 읽기 실패"
categories=dict()
# 새로운 dict에 카테고리id : 카테고리 이름
for category in coco_info['categories']:
categories[category["id"]]=category["name"]
print(categories)
ann_info=dict()
# 새로운 dict에 이미지아이디 : bbox, 카테고리id
for annotation in coco_info['annotations']:
image_id =annotation["image_id"]
bbox=annotation["bbox"]
category_id=annotation["category_id"]
if image_id not in ann_info:
ann_info[image_id] ={
"boxes":[bbox],"categories":[category_id]
}
else :
ann_info[image_id]["boxes"].append(bbox)
ann_info[image_id]["categories"].append(categories[category_id])
print(ann_info)
for image_info in coco_info['images']:
filename=image_info["file_name"]
height=image_info['height']
width=image_info["width"]
img_id=image_info["id"]
file_path=os.path.join("./raccoon/data/",filename)
img=cv2.imread(file_path)
print(file_path)
#./raccoon/data/raccoon-91_jpg.rf.zdghE2k81QF9RDOjL2Aw.jpg
try:
annotation = ann_info[img_id]
print(annotation)
#{'boxes': [[16, 21, 300, 332]], 'categories': [1]}
except KeyError:
continue
for bbox,category in zip(annotation["boxes"],annotation["categories"]):
x1,y1,w,h=bbox
font=cv2.FONT_HERSHEY_SIMPLEX
fontScale=1
color=(255,0,0)
thickness=2
org_img=img.copy()
print(org_img.shape)
#이미지 자르기
#자른후 height, width 가져와서 padding넣어줌
crop_img=org_img[int(y1):int(y1+h),int(x1):int(x1+w)]
crop_height,crop_width=crop_img.shape[0:2]
margin=[np.abs(crop_height-crop_width)//2,np.abs(crop_height-crop_width)//2]
if np.abs(crop_height-crop_width)%2 != 0:
margin[0]+=1
if crop_height<crop_width:
margin_list=[margin,[0,0]]
else:
margin_list=[[0,0],margin]
print(margin_list)
if len(crop_img.shape)==3:
margin_list.append([0,0])
margin_img=np.pad(crop_img,margin_list,mode='constant')
#이미지 resize
resize_img=cv2.resize(margin_img,(255,255))
save_path="./raccoon/image_result/"
os.makedirs(save_path,exist_ok=True)
cv2.imwrite(os.path.join(save_path,filename), resize_img)
#cv2.imshow("test",resize_img)
#cv2.waitKey(0)
실행결과
학습한 내용
import os
import json
import cv2
import numpy as np
import pandas as pd
json_path="./raccoon/anno/raccoon_annotations.coco.json"
with open(json_path,"r") as f:
coco_info=json.load(f)
# len(coco_info)>0이 아니면 파일 읽기 실패
assert len(coco_info)>0,"파일 읽기 실패"
#이미지 id, bbox가져오기
ann_info=dict()
for annotation in coco_info['annotations']:
image_id =annotation["image_id"]
bbox=annotation["bbox"]
if image_id not in ann_info:
ann_info[image_id] ={
"boxes":[bbox]
}
else :
ann_info[image_id]["boxes"].append(bbox)
print(ann_info)
# 빈 dict 생성
data={'file_name':[],'box_x':[],'box_y':[],'box_w':[],'box_h':[]}
for image_info in coco_info['images']:
filename=image_info["file_name"]
img_id=image_info["id"]
try:
annotation = ann_info[img_id]
print(annotation)
except KeyError:
continue
for bbox in annotation["boxes"]:
x1,y1,w,h=bbox
data['file_name'].append(filename)
data['box_x'].append(x1)
data['box_y'].append(y1)
data['box_w'].append(w)
data['box_h'].append(h)
# filename, x,y,w,h,저장
data=pd.DataFrame(data)
data.to_csv('./raccoon/정성우.csv',index=False)
실행결과
학습한 내용 중 어려웠던 점 또는 해결못한 것들
해결방법 작성
학습 소감
제공되는 annotation파일을 보고 이미지에 box를 그리거나 자르는게 재미있었다.