본문 바로가기

프로젝트/(Vision)이미지 검색 및 상품추천

개발일지 (2) - detection 결과물을 JSON출력하기

지난 과정에서 retinanet을 이용해 object detection 결과물을 얻었다.

 

그 결과물을  COCO JSON 형식으로 출력하는 것이 본 포스팅의 목표이다.

 

img 출력형식

detection box의 출력 형식은 label index와 (좌상단y, 좌상단x, 우하단y, 우하단 x) 로 이루어져 있다.

 

 

# load image
imagePath = "beatles01.jpg"
image = read_image_bgr('../../data/image/'+imagePath)
print('image shape:', image.shape)
# copy to draw on
draw = image.copy()
draw = cv2.cvtColor(draw, cv2.COLOR_BGR2RGB)


# 모델에 입력전에 이미지 사전 처리. keras-retinanet은 image
image = preprocess_image(image)
image, scale = resize_image(image)
print('resized image size:', image.shape, 'scale:', scale)

# 이미지에 대해 Object Detection 수행. 
start = time.time()
boxes, scores, labels = retina_model.predict_on_batch(np.expand_dims(image, axis=0))
print(boxes.shape, scores.shape, labels.shape)
print("processing time: ", time.time() - start)

# correct for image scale
boxes /= scale

# JSON 출력 결과를 저장할 배열
resultsForJSON = []

# visualize detections
for box, score, label in zip(boxes[0], scores[0], labels[0]):
    # scores are sorted so we can break
    if score < 0.5:
        break
    
    # JSON 출력 내용 입력
    resultsForJSON.append({"shapes":[{"label": labels_to_names_seq[label],
                           "points": [
                               [
                                   float(b[0]),
                                   float(b[1])
                               ],
                               [
                                   float(b[2]),
                                   float(b[3])
                               ]
                           ],
                           "group_Id": "null",
                           "shape_type": "rectangle",
                           "flags": {}
                                     }
                            ],
                           "imagePath": str(imagePath),
                           "imageHeight": int(b[2]-b[0]),
                           "ImageWidth": int(b[3]-b[1])
                          }
                         )
    
    color = label_color(label)

    b = box.astype(int)
    
    draw_box(draw, b, color=color)
    
    caption = "{} {:.3f}".format(labels_to_names_seq[label], score)
    draw_caption(draw, b, caption)


# 배열을JSON 파일로 dumps
# indent=4로 설정하여 보기 좋게 만듬
# JSON 파일명은 경로명 + .json(파일 서식)
textJSON = json.dumps(resultsForJSON, indent=4)
textFile = imagePath + ".json"
with open(textFile, 'w') as f:
    f.write(textJSON)

plt.figure(figsize=(14, 14))
plt.axis('off')
plt.imshow(draw)
plt.show()

 

위 코드에서 주석으로 표시한 부분을 추가해주면

 

JSON 출력 결과

위처럼 JSON파일을 dump할 수 있다.

 

참고 사이트

github.com/thtrieu/darkflow/issues/336

 

Prediction: generating bounding box and json files at once · Issue #336 · thtrieu/darkflow

How could I generated bb and json files for prediction at once?

github.com

www.javaprogramto.com/2019/11/python-typeerror-integer-json-not-serializable.html

 

Python - TypeError: Object of type 'int64' is not JSON serializable (Works for all data types - Integer, Float, Array, etc)

Java Tutorials for Freshers and Experience developers, Data Structure and Algorithms interview Programs, Kotlin programs, Java 8 Stream, Spring Boot.

www.javaprogramto.com

pythonq.com/so/python/1823687

 

python - 파이썬으로 작성된 JSON에 줄 바꿈 추가 - IT 툴 넷

python - 파이썬으로 작성된 JSON에 줄 바꿈 추가 출처 python json couchdb line-breaks

pythonq.com