• 카테고리

    질문 & 답변
  • 세부 분야

    컴퓨터 비전

  • 해결 여부

    미해결

inference 결과로 출력된 segmentation 혹은 object detection 정보를 json 이나 xml로 출력

23.01.02 13:58 작성 조회수 348

0

inference 결과로 출력된 segmentation 혹은 object detection 정보를 json 이나 xml로 출력하고 싶어요. 이런 경우에 해당하는 예제나 관련 파일이 혹시 있을까요? 항상 감사합니다!

답변 1

답변을 작성해보세요.

1

안녕하십니까,

이건 저도 잘 모르겠습니다.

mmdetection에서 아마 output을 json으로 하는 API를 만든것 같은데, 어디 있는지 잘 찾지를 못하겠군요.

제 생각으로는 굳이 api를 찾지 마시고 결과를 json으로 만들어버리면 될 것 같습니다만,

원하는 json format을 설정하시고 거기에 값을 그냥 넣으면 될 것 같습니다.

만들고자 하는 json 포맷이 어떻게 되는지는 잘 모르겠지만,

가령 예를 들어 json 자료형을 파이썬에서 아래와 같이 설정하고

json_dict = {

"image_filename": "파일명",

"bbox": [bbox 추출 결과],

"segmentation": [ segmentation 추출결과],

"classes": [클래스명]

}

과 같이 직접 json 자료형을 파이썬 딕셔너리 형태로 만드신 다음에 아래와 같이 json 파일로 만드시면 될 것 같습니다.

import json

json_data = json.dump(dict)

 

감사합니다.

고재청님의 프로필

고재청

질문자

2023.01.04

답변 감사드립니다. 한번 시도해 보겠습니다!

고재청님의 프로필

고재청

질문자

2023.01.06

import cv2
import mrcnn.model as modellib
from mrcnn.visualize import InferenceConfig, get_mask_contours, random_colors, draw_mask
import numpy
import json

# Load MaskRCNN model
num_classes = 4
config = InferenceConfig(num_classes=num_classes, image_size=1024) # class 숫자와 image 사이즈 입력
model = modellib.MaskRCNN(mode="inference", config=config, model_dir="")
model.load_weights(filepath="dnn_model/mask_rcnn_object_0003.h5", by_name=True)

# Load image
img = cv2.imread("images/val06.jpg")
image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# Detect objects
results = model.detect([image])[0]  # 우린 4개 검출해야함
class_ids = results["class_ids"]
object_count = len(class_ids)

# Random colors
colors = random_colors(object_count)

for i in range(object_count):
    # 1.class ID
    class_id = results["class_ids"][i]

    # 2.Box
    box = results["rois"][i]
    y1, x1, y2, x2 = box
    cv2.rectangle(img, (x1, y1), (x2, y2), colors[i], 2)

    # 3.Score
    score = scores = results["scores"][i]

    # 4.Mask
    mask = results["masks"][:,:,i]
    contours = get_mask_contours(mask)
    print("Contours", contours)
    for cnt in contours:
        cv2.polylines(img, [cnt], True, colors[i],2)
        img = draw_mask(img, [cnt], colors[i], alpha=0.5)

    # json dictionary
    json_dict = {
        "image_filename": img,
        "bbox": [box],
        "segmentation": [contours],
        "classes": [class_id]
    }
    json_data = json.dumps(json_dict, indent=2)
    print(json_data)

# Display image
cv2.imshow("Img", img)
cv2. waitKey(0)

이렇게 코드를 수정해서 돌려보는데

 

Traceback (most recent call last):

File "C:\Users\Jae\PycharmProjects\MaskRCNN_Jae\demo.py", line 52, in <module>

json_data = json.dumps(json_dict, indent=2)

File "C:\Users\Jae\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 234, in dumps

return cls(

File "C:\Users\Jae\AppData\Local\Programs\Python\Python39\lib\json\encoder.py", line 201, in encode

chunks = list(chunks)

File "C:\Users\Jae\AppData\Local\Programs\Python\Python39\lib\json\encoder.py", line 431, in _iterencode

yield from iterencodedict(o, currentindent_level)

File "C:\Users\Jae\AppData\Local\Programs\Python\Python39\lib\json\encoder.py", line 405, in iterencodedict

yield from chunks

File "C:\Users\Jae\AppData\Local\Programs\Python\Python39\lib\json\encoder.py", line 438, in _iterencode

o = _default(o)

File "C:\Users\Jae\AppData\Local\Programs\Python\Python39\lib\json\encoder.py", line 179, in default

raise TypeError(f'Object of type {o.__class__.__name__} '

TypeError: Object of type ndarray is not JSON serializable

Process finished with exit code 1

 

이런 에러가 나옵니다. numpy array 를 리스트로 변환해야 한다는데... tolist 를 써도 변환이 안되네요.. 혹시 한번만 살펴봐 주실 수 있나요...감사합니다.

image_filename 은 이미지 파일명 같은데 img를 할당하면 img는 image array로 원하는 결과가 나오지 않을 것 같습니다. image_filename을 문자열로 변경해 보시지요.