最近在做目标识别的算法,需要对给定的数据进行格式转换,需要先画出来看看
import cv2
import numpy as np
import math
def draw(img, result):
# 下面几个参数,可能需要根据自己的数据进行调整
x = int(result[0][0]) # 矩形框的中心点x
y = int(result[0][1]) # 矩形框的中心点y
angle = result[2] # 矩形框的倾斜角度(长边相对于水平)
width, height = int(result[1][0]), int(result[1][1]) # 矩形框的宽和高
# if result[1][0] > result[1][1]:
# height, width = int(result[1][0]), int(result[1][1])
# else:
# height, width = int(result[1][1]), int(result[1][0])
anglePi = angle * math.pi / 180.0 # 计算角度
cosA = math.cos(anglePi)
sinA = math.sin(anglePi)
x1 = x - 0.5 * width
y1 = y - 0.5 * height
x0 = x + 0.5 * width
y0 = y1
x2 = x1
y2 = y + 0.5 * height
x3 = x0
y3 = y2
x0n = (x0 - x) * cosA - (y0 - y) * sinA + x
y0n = (x0 - x) * sinA + (y0 - y) * cosA + y
x1n = (x1 - x) * cosA - (y1 - y) * sinA + x
y1n = (x1 - x) * sinA + (y1 - y) * cosA + y
x2n = (x2 - x) * cosA - (y2 - y) * sinA + x
y2n = (x2 - x) * sinA + (y2 - y) * cosA + y
x3n = (x3 - x) * cosA - (y3 - y) * sinA + x
y3n = (x3 - x) * sinA + (y3 - y) * cosA + y
# 根据得到的点,画出矩形框
cv2.line(img, (int(x0n), int(y0n)), (int(x1n), int(y1n)), (0, 0, 255), 1, 4)
cv2.line(img, (int(x1n), int(y1n)), (int(x2n), int(y2n)), (0, 0, 255), 1, 4)
cv2.line(img, (int(x2n), int(y2n)), (int(x3n), int(y3n)), (0, 0, 255), 1, 4)
cv2.line(img, (int(x0n), int(y0n)), (int(x3n), int(y3n)), (0, 0, 255), 1, 4)
data = [(1275, 458), (1494, 88), (1418, 43), (1200, 414), (1275, 458)]
img_pth = r"E:\BaiduNetdiskDownload\FAIR1M\train\part1\images\0.tif"
img = cv2.imread(img_pth)
sp = img.shape
print(sp[0], sp[1])
for i in range(0, len(data) - 1):
cv2.line(img, data[i], data[i + 1], (0, 255, 0), 1, 4)
data = np.array(data)
rect = cv2.minAreaRect(data) # 得到最小外接矩形的(中心(x,y), (宽,高), 旋转角度)
cv2.circle(img, (int(rect[0][0]), int(rect[0][1])), 1, (0, 0, 255), 4) # 画中心点
draw(img, rect)
print(rect)
cv2.namedWindow("image", cv2.WINDOW_AUTOSIZE)
cv2.imshow('image', img)
cv2.waitKey(10000) # 显示 10000 ms 即 10s 后消失
cv2.destroyAllWindows()