opencv-python学习-几何形状拟合的报错----附上个人报错后修改的小意见
下方是源程序
#coding:utf-8
import cv2
import numpy as np
def draw_rect(img_file, points):
img = cv2.imread(img_file)
center, size, angle = cv2.minAreaRect(points) #中心点坐标,尺寸,旋转角度
print(center, size, angle)
vertices= cv2.boxPoints((center, size, angle))
print(vertices)
for i in range(4):
point1 = vertices[i, :]
point2 = vertices[(i+1)%4, :]
cv2.line(img, tuple(point1), tuple(point2), (0, 0, 255), 2)
cv2.imshow("img", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == "__main__":
img_file = r"D:\data\timg.jpg"
points1 = np.array([[154, 154],[253, 171], [154, 176],[248, 204]], np.int32) # 数据类型为int32或者float32
draw_rect(img_file, points1)
# points2 = np.array([[148, 171], [247, 153], [253, 186], [154, 204]], np.int32)
# draw_rect(img_file, points2)
minAreaRect()
运行后会出现关于数据类型的报错---错误在cv2.line(img,tuple(point1),tuple(point2), (0,0,255), 2)的列表数据类型有误 该处指向的是整数型 但是代码中的vertices为float型 需要进行数据转换
(201.0, 179.00001525878906) (101.1060562133789, 33.37017059326172) 9.743640899658203
[[148.35242 186.88881]
[154. 154.00002]
[253.64758 171.11122]
[248. 204.00002]]
Traceback (most recent call last):
File "F:\py3e_source\chapter11\eyeganzhi4.py", line 27, in
draw_rect(img_file, points1)
File "F:\py3e_source\chapter11\eyeganzhi4.py", line 16, in draw_rect
cv2.line(img,tuple(point1),tuple(point2), (0,0,255), 2)
cv2.error: OpenCV(4.5.3) :-1: error: (-5:Bad argument) in function 'line'
> Overload resolution failed:
> - Can't parse 'pt1'. Sequence item with index 0 has a wrong type
> - Can't parse 'pt1'. Sequence item with index 0 has a wrong type
此处为我修改过后的示例:(列表数据转换有多种 此处仅列举一种)
import cv2
import numpy as np
def draw_rect(img_file, points):
img = cv2.imread(img_file)
center, size, angle = cv2.minAreaRect(points) #中心点坐标,尺寸,旋转角度
print(center, size, angle)
vertices= cv2.boxPoints((center, size, angle))
print(vertices)
for i in range(4):
point1 = vertices[i, :]
point1 = [int(j) for j in point1]
print(point1)
point2 = vertices[(i+1)%4, :]
point2 = [int(j) for j in point2]
cv2.line(img,tuple(point1),tuple(point2), (0,0,255), 2)
cv2.imshow("img", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == "__main__":
img_file = r"tlgd.jpg"
points1 = np.array([[154, 154],[253, 171], [154, 176],[248, 204]], np.int32) # 数据类型为int32或者float32
draw_rect(img_file, points1)
改正后程序可以正常运行!!!
今天你学废了吗!!!