inference 결과로 출력된 segmentation 혹은 object detection 정보를 json 이나 xml로 출력
571
작성한 질문수 17
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)
감사합니다.
0
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 를 써도 변환이 안되네요.. 혹시 한번만 살펴봐 주실 수 있나요...감사합니다.
0
image_filename 은 이미지 파일명 같은데 img를 할당하면 img는 image array로 원하는 결과가 나오지 않을 것 같습니다. image_filename을 문자열로 변경해 보시지요.
MMDetection 버전 이슈
0
19
2
강의 환경설정 질문
0
44
2
Custom Dataset에서의 polygon 정보 관련
0
90
3
cvat.ai 보안 수준이 궁금합니다
0
82
2
캐클 nucleus 챌린지 runpod 실습 코드 에러 질문드립니다.
0
103
3
추론 결과의 Precision(또는 mAP) 평가 방법
0
88
2
mmdetection mask rcnn inferenct 실습 시 runpod 템플릿 관해서 질문드립니다.
0
61
2
runpod에서 google drive 연결 시 오류 발생
0
114
2
로드맵 선택
0
69
1
mmcv
0
61
2
Anchor box의 Positive 처리 위치
0
66
2
해당 강의 runpod 적용 후 에러 제보드립니다
0
90
2
run pod credit 관련 제보
0
105
2
mmdetection 2.x과 3.x 호환 관련 표기
0
80
2
mm_faster_rcnn_train_kitti.ipynb 실행 오류
0
102
3
질문 드립니다.
0
85
3
mm_faster_rcnn_train_coco_bccd 실행 오류 질문드립니다.
0
82
1
강사님께 수정을 제안드리고 싶은 것이 있습니다.
0
97
1
google automl efficientdet 다운로드 및 설치 오류
0
78
1
이상 탐지에 사용할 비전 기술 조언 부탁드립니다.
0
104
2
OpenCV 관련 질문드립니다.
0
76
2
mmcv 설치관련해서 문의드려요
0
339
3
강의 구성 관련해서 질문이 있습니다
1
139
2
모델 변환 성능 질문드립니다.
0
123
1





