【发布时间】:2017-07-02 23:22:51
【问题描述】:
我是 python 新手,我正在尝试编写一个代码,从图像中提取轮廓并按照轮廓列表中元素长度的升序对它们进行排序。当我使用 sort() 或 list.sort() 时,出现错误:操作数无法与形状一起广播 (1776,1,2) (3896,1,2) 我该如何解决这个问题? 这是我正在使用的image。
我得到的错误信息是:
Traceback (most recent call last):
File "/home/dehaoliu/opencv_test/Engineering drawings/example.py", line 19, in <module>
contours.sort()
ValueError: operands could not be broadcast together with shapes (1776,1,2) (3896,1,2)
以下是产生错误的缩短代码:
import cv2
import numpy as np
from math import sqrt
name='20_right_5-1'
img = cv2.imread(name+'.JPG')
im = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
cv2.imwrite(name+"_dilation.jpg", closing)
im = cv2.imread(name+'_dilation.jpg')
imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
#ret,thresh = cv2.threshold(imgray,127,255,cv2.THRESH_BINARY_INV)
blur = cv2.GaussianBlur(imgray,(5,5),0)
ret,thresh = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
cv2.drawContours(im, contours, -1, (0,255,0), 3)
cv2.namedWindow("Contours")
cv2.imshow("Contours", im)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite(name+"_contour.jpg", im)
print "this is contours"
print contours
print type(contours)
contours.sort()
【问题讨论】:
-
让错误消失很容易,但要确保结果是您想要的结果却不太容易。您是否了解错误中的这些维度,以及您的预期结果应该是什么大小?
-
我相信它们是列表中第一个和第二个元素的尺寸
-
对不起,如果这是一个愚蠢的问题。我以前没有使用 python 的经验,我一直在尝试解决这个问题。
-
是的,但他们的目的是什么?我的观点是,我可以告诉你如何制作尺寸以使其广播,例如,结果可能具有
(1776,3896,1,2)的形状。但这是否有意义是另一回事,您应该了解正在发生的事情以及您到底想做什么。 -
我刚刚添加了错误信息。我真的很感谢你告诉我这件事。谢谢!
标签: python python-2.7 image-processing