https://blog.csdn.net/mary_0830/article/details/103212958
更新于2021.3.24
import cv2
import pandas as pd
import json
import os
# ground-truth
# def select(json_path, outpath, image_path):
# json_file = open(json_path)
# infos = json.load(json_file)
# images = infos["images"]
# annos = infos["annotations"]
# assert len(images) == len(images)
# # import pdb;pdb.set_trace()
# for i in range(len(images)):
# im_id = images[i]["id"]
# im_path = image_path + images[i]["file_name"]
# img = cv2.imread(im_path)
# for j in range(len(annos)):
# if annos[j]["image_id"] == im_id:
# x, y, w, h = annos[j]["bbox"]
# x, y, w, h = int(x), int(y), int(w), int(h)
# x2, y2 = x + w, y + h
# # object_name = annos[j][""]
# img = cv2.rectangle(img, (x, y), (x2, y2), (0, 255, 0), thickness=1)
# img_name = outpath + images[i]["file_name"]
# # import pdb;pdb.set_trace()
# cv2.imwrite(img_name, img)
# # continue
# # print(i)
# predict
def select(json_path, outpath, image_path):
json_file = open(json_path)
infos = json.load(json_file)
for i in range(len(infos)):
im_id = infos[i]["image_id"]
im_path = image_path + str(infos[i]["image_id"]) + '.jpg'
# import pdb;pdb.set_trace()
img_name = outpath + str(infos[i]["image_id"]) + '.jpg'
score = str(infos[i]["score"])
if not os.path.exists(img_name):
img = cv2.imread(im_path)
else:
img = cv2.imread(img_name)
if float(score) < 0.2 or float(score) > 0.5:
continue
else:
x, y, w, h = infos[i]["bbox"]
x, y, w, h = int(x), int(y), int(w), int(h)
x2, y2 = x + w, y + h
c_x, c_y = int((x + x2) / 2), int((y + y2) / 2)
cla = str(infos[i]["category_id"])
cv2.rectangle(img, (x, y), (x2, y2), (0, 255, 0), thickness=1)
cv2.putText(img, score, (x, y + 5), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
cv2.putText(img, cla,(c_x, c_y), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)
img_name = outpath + str(infos[i]["image_id"]) + '.jpg'
cv2.imwrite(img_name, img)
print("Done!")
if __name__ == "__main__":
json_path = 'XXX.json'
image_path = '/X/'
outpath = '/X/'
select(json_path, outpath, image_path)
更新于2021.4.13
#coding:utf-8
import numpy as np
import os
import cv2
# from Constants import final_detect_result,VIII_visual_dir
import json
def compute_IOU(rec1,rec2):
"""
计算两个矩形框的交并比。
:param rec1: (x0,y0,x1,y1) (x0,y0)代表矩形左上的顶点,(x1,y1)代表矩形右下的顶点。下同。
:param rec2: (x0,y0,x1,y1)
:return: 交并比IOU.
"""
left_column_max = max(rec1[0],rec2[0])
right_column_min = min(rec1[2],rec2[2])
up_row_max = max(rec1[1],rec2[1])
down_row_min = min(rec1[3],rec2[3])
#两矩形无相交区域的情况
if left_column_max>=right_column_min or down_row_min<=up_row_max:
return 0
# 两矩形有相交区域的情况
else:
S1 = (rec1[2]-rec1[0])*(rec1[3]-rec1[1])
S2 = (rec2[2]-rec2[0])*(rec2[3]-rec2[1])
S_cross = (down_row_min-up_row_max)*(right_column_min-left_column_max)
return S_cross/(S1+S2-S_cross)
def readNameId():
fp = open("name_id_val.txt","r")
lines = [i.strip('\n').split(",") for i in fp.readlines()]
data = {}
for line in lines:
name,newid = line
data[newid] = name
return data
def draw_bboxes(image, bboxes, font_size=0.5, thresh=0.5, colors=None):
image = image.copy()
coco_cls_names = [
'pedestrian','people',
'bicycle','car','van','truck','tricycle',
'awning-tricycle','bus','motor'
]
if colors is None:
color = np.random.random((3, )) * 0.6 + 0.4
color = (color * 255).astype(np.int32).tolist()
for box in bboxes:
if box[4] <thresh:
continue
# print(box[4])
cat_name = coco_cls_names[box[5]-1]
cat_size = cv2.getTextSize(cat_name, cv2.FONT_HERSHEY_SIMPLEX, font_size, 2)[0]
bbox = np.array([box[0],box[1],box[2],box[3]]).astype(int)
# if bbox[1] - cat_size[1] - 2 < 0:
# cv2.rectangle(image,
# (bbox[0], bbox[1] + 2),
# (bbox[0] + cat_size[0], bbox[1] + cat_size[1] + 2),
# (255,0,0), -1
# )
# cv2.putText(image, cat_name,
# (bbox[0], bbox[1] + cat_size[1] + 2),
# cv2.FONT_HERSHEY_SIMPLEX, font_size, (0, 0, 0), thickness=1
# )
# else:
# cv2.rectangle(image,
# (bbox[0], bbox[1] - cat_size[1] - 2),
# (bbox[0] + cat_size[0], bbox[1] - 2),
# (255,0,0), -1
# )
# cv2.putText(image, cat_name,
# (bbox[0], bbox[1] - 2),
# cv2.FONT_HERSHEY_SIMPLEX, font_size, (0, 0, 0), thickness=1
# )
cv2.rectangle(image,
(bbox[0], bbox[1]),
(bbox[2], bbox[3]),
(0,255,255), 2
)
return image
def readFinalResult():
fp = open('xxx.json')
boxes = json.load(fp)
data = {}
for bbox in boxes:
img_id = bbox["image_id"]
x1,y1,x2,y2 = bbox["bbox"]
cat_id = bbox["category_id"]
score = bbox["score"]
if not img_id in data.keys():
data[img_id] = []
data[img_id].append([x1,y1,x1+x2,y1+y2,score,cat_id])
# import pdb; pdb.set_trace()
return data
if __name__ =="__main__":
imgDir = "/images/"
nameIdArr = readNameId()
# import pdb; pdb.set_trace()
images = [i for i in os.listdir(imgDir) if '.jpg' in i]
print('find image', len(images))
data = readFinalResult()
for idx,img_name in enumerate(images):
if idx>550:
break
imgpath = os.path.join(imgDir, img_name)
img_data = cv2.imread(imgpath, -1)
# print("img path:",imgpath)
height, width = img_data.shape[:2]
# import pdb; pdb.set_trace()
# newimg = draw_bboxes(img_data, data[nameIdArr[img_name[:-4]]])
newimg = draw_bboxes(img_data, data[int(img_name[:-4])])
save_path = os.path.join('/',img_name)
cv2.imwrite(save_path , newimg)
print('Done!')
https://blog.csdn.net/mary_0830/article/details/108776419(第五点)
import os
import os.path
import xml.etree.cElementTree as ET
import cv2
def draw(image_path, xml_path, root_saved_path):
"""
图片根据标注画框
"""
src_img_path = image_path
src_ann_path = xml_path
for file in os.listdir(src_ann_path):
# print(file)
file_name, suffix = os.path.splitext(file)
# import pdb
# pdb.set_trace()
if suffix == '.xml':
# print(file)
xml_path = os.path.join(src_ann_path, file)
image_path = os.path.join(src_img_path, file_name+'.jpg')
img = cv2.imread(image_path)
tree = ET.parse(xml_path)
root = tree.getroot()
# import pdb
# pdb.set_trace()
for obj in root.iter('object'):
name = obj.find('name').text
xml_box = obj.find('bndbox')
x1 = int(xml_box.find('xmin').text)
x2 = int(xml_box.find('xmax').text)
y1 = int(xml_box.find('ymin').text)
y2 = int(xml_box.find('ymax').text)
cv2.rectangle(img, (x1, y1), (x2, y2), (255, 0, 0), thickness=2)
# 字为绿色
# cv2.putText(img, name, (x1, y1), cv2.FONT_HERSHEY_COMPLEX, 0.7, (0, 255, 0), thickness=2)
cv2.imwrite(os.path.join(root_saved_path, file_name+'.jpg'), img)
if __name__ == '__main__':
image_path = "D:/datasets/VisDrone/VisDrone2019-DET-train/images_600"
xml_path = "D:/datasets/VisDrone/VisDrone2019-DET-train/annotations_600"
root_saved_path = "D:/datasets/VisDrone/VisDrone2019-DET-train/result"
draw(image_path, xml_path, root_saved_path)
visualization_results.py
import json
import shutil
import cv2
# ---------------------------json画框
def select(json_path, outpath, image_path):
json_file = open(json_path, 'r')
infos = json.load(json_file)
for i in infos:
images = i["image_id"]
if i['score'] >= 0.5:
if i['image_id']!= images:
img = cv2.imread(image_path + images + '.jpg')
else:
# 换成你自己的类别
img = cv2.imread(outpath + images + '.jpg')
x1, y1 = int(i['bbox'][0]), int(i['bbox'][1])
w, h = int(i['bbox'][2]), int(i['bbox'][3])
x2, y2 = x1 + w, y1 + h
img = cv2.rectangle(img, (x1, y1), (x2, y2), (255, 255, 0), thickness=1)
img_name = outpath + images + '.jpg'
# import pdb
# pdb.set_trace()
cv2.imwrite(img_name, img)
if __name__ == "__main__":
json_path = "xxx/results_cluster.json"
out_path = "xxx/visualization_output/"
image_path = "xxx/images_cluster/"
select(json_path, out_path, image_path)
更新于2021.5.10
import cv2
# import pandas as pd
import json
import os
# ground-truth
# def select(json_path, outpath, image_path):
# json_file = open(json_path)
# infos = json.load(json_file)
# images = infos["images"]
# annos = infos["annotations"]
# assert len(images) == len(images)
# # import pdb;pdb.set_trace()
# for i in range(len(images)):
# im_id = images[i]["id"]
# im_path = image_path + images[i]["file_name"]
# img = cv2.imread(im_path)
# for j in range(len(annos)):
# if annos[j]["image_id"] == im_id:
# x, y, w, h = annos[j]["bbox"]
# x, y, w, h = int(x), int(y), int(w), int(h)
# x2, y2 = x + w, y + h
# # object_name = annos[j][""]
# img = cv2.rectangle(img, (x, y), (x2, y2), (0, 255, 0), thickness=1)
# img_name = outpath + images[i]["file_name"]
# # import pdb;pdb.set_trace()
# cv2.imwrite(img_name, img)
# # continue
# # print(i)
# predict
def select(json_path, outpath, image_path):
json_file = open(json_path)
infos = json.load(json_file)
for i in range(len(infos)):
im_id = infos[i]["image_id"]
im_path = image_path + str(infos[i]["image_id"]) + '.jpg'
# import pdb;pdb.set_trace()
img_name = outpath + str(infos[i]["image_id"]) + '.jpg'
score = str(infos[i]["score"])
if not os.path.exists(img_name):
img = cv2.imread(im_path)
else:
img = cv2.imread(img_name)
# if float(score) < 0.5:
# continue
# else:
x, y, w, h = infos[i]["bbox"]
x, y, w, h = int(x), int(y), int(w), int(h)
x2, y2 = x + w, y + h
c_x, c_y = int((x + x2) / 2), int((y + y2) / 2)
cla = str(infos[i]["category_id"])
# import pdb;pdb.set_trace()
# img = cv2.rectangle(img, (x, y), (x2, y2), (0, 255, 255), thickness=2)
if float(score) <= 0.3:
cv2.circle(img, (c_x, c_y), 5, (0,0,int(255*float(score))), -1) # red
continue
elif float(score) > 0.3 and float(score) <= 0.6:
cv2.circle(img, (c_x, c_y), 5, (int(255*float(score)),255,0), -1) # green
elif float(score) > 0.6:
cv2.circle(img, (c_x, c_y), 5, (0,int(255*float(score)),255), -1) # yellow
# cv2.rectangle(img, (x, y), (x2, y2), (0, 0, 255), thickness=2)
# cv2.putText(img, score, (x, y + 5), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
# cv2.putText(img, cla,(c_x, c_y), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)
img_name = outpath + str(infos[i]["image_id"]) + '.jpg'
# import pdb;pdb.set_trace()
cv2.imwrite(img_name, img)
print("Done!")
if __name__ == "__main__":
json_path = 'results.json'
image_path = '/images/'
outpath = '/output/'
select(json_path, outpath, image_path)