labelme 标注数据生成最小外接矩形的旋转角度
import json
import math
import cv2
import numpy as np
import math
j_file= '0011_rgb.json'
p_file='0011_rgb.jpg'
with open(j_file, "r") as j_f:
data=json.load(j_f)
img=cv2.imread(p_file)
contours=[]
rects=[]
font = cv2.FONT_HERSHEY_SIMPLEX
for shape in data['shapes']:
points=shape['points']
# points=[[x] for x in points ]
contour=np.array(points,np.int32)
contours.append(contour)
rect = cv2.minAreaRect(contour)
rects.append(rect)
for rect in rects:
x, y = rect[0]
width,height=rect[1]
angle=rect[2]
if width>height:
l=(width+100)/2
ptStart = (int(x-l*math.cos(math.pi/(180)*angle)), int(y-l*math.sin(math.pi/(180)*angle)))
ptEnd = (int(x+l*math.cos(math.pi/(180)*angle)), int(y+l*math.sin(math.pi/(180)*angle)))
point_color = (0, 255, 0) # BGR
thickness = 1
lineType = 4
cv2.line(img, ptStart, ptEnd, point_color, thickness, lineType)
cv2.putText(img, str(int(-angle)), (int(x), int(y)), font, 1.2, (255, 255, 255), 2)
else:
l=(height+100)/2
ptStart = (int(x-l*math.cos(math.pi/(180)*(90+angle))), int(y-l*math.sin(math.pi/(180)*(90+angle))))
ptEnd = (int(x+l*math.cos(math.pi/(180)*(90+angle))), int(y+l*math.sin(math.pi/(180)*(90+angle))))
point_color = (0, 255, 0) # BGR
thickness = 1
lineType = 4
cv2.line(img, ptStart, ptEnd, point_color, thickness, lineType)
cv2.putText(img, str(int(90-angle)), (int(x), int(y)), font, 1.2, (255, 255, 255), 2)
cv2.circle(img, (int(x), int(y)), 3, (0, 255, 0), 5)
print(width,height)
cv2.drawContours(img,contours,-1,(0,255,0),1)
rect = cv2.minAreaRect(contours[0])
cv2.imshow("contours",img)
cv2.waitKey(0)
cv2.destroyAllWindows()