【发布时间】:2018-07-05 03:08:02
【问题描述】:
运行代码时出现图像类型错误。我知道 HoughLinesP 需要灰度图像,但是当我尝试将源图像转换为灰度时,出现以下错误(1):
错误:(-215) 深度 == 0 ||深度 == 2 ||函数 cv::cvtColor 中的深度 == 5
如果我在未转换为灰度的情况下运行 HoughLinesP,则会收到以下错误 (2):
错误:(-215) image.type() == (((0) & ((1
我不知道需要什么转换才能摆脱错误
这是发生错误的代码:
#extract largest component from image.
components, output, stats, centroids = cv2.connectedComponentsWithStats(threshold_img, connectivity=4)
sizes = stats[:, -1]
max_label = 1
max_size = sizes[1]
for i in range(2, components):
if sizes[i] > max_size:
max_label = i
max_size = sizes[i]
biggestComponent = np.zeros(output.shape)
biggestComponent[output == max_label] = 255
biggestComponent = biggestComponent - cv2.erode(biggestComponent, np.ones((5,5), np.uint8))
dilated = cv2.dilate(biggestComponent, np.ones((3,3), dtype=np.uint8))
#-------------------------ERROR(1)----------------------------#
dilated = cv2.cvtColor(dilated, cv2.COLOR_BGR2GRAY)
#obtaining corners using houghlines
def find_intersection(line1, line2):
# extract points
x1, y1, x2, y2 = line1[0]
x3, y3, x4, y4 = line2[0]
# compute determinant
Px = ((x1*y2 - y1*x2)*(x3-x4) - (x1-x2)*(x3*y4 - y3*x4))/ \
((x1-x2)*(y3-y4) - (y1-y2)*(x3-x4))
Py = ((x1*y2 - y1*x2)*(y3-y4) - (y1-y2)*(x3*y4 - y3*x4))/ \
((x1-x2)*(y3-y4) - (y1-y2)*(x3-x4))
return Px, Py
def segment_lines(lines, delta):
h_lines = []
v_lines = []
for line in lines:
for x1, y1, x2, y2 in line:
if abs(x2-x1) < delta: # x-values are near; line is vertical
v_lines.append(line)
elif abs(y2-y1) < delta: # y-values are near; line is horizontal
h_lines.append(line)
return h_lines, v_lines
def cluster_points(points, nclusters):
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
_, _, centers = cv2.kmeans(points, nclusters, None, criteria, 10, cv2.KMEANS_PP_CENTERS)
return centers
#-------------------------ERROR(2)----------------------------#
# run the Hough transform
lines = cv2.HoughLinesP(dilated, rho=1, theta=np.pi/180, threshold=100, maxLineGap=20, minLineLength=50)
【问题讨论】:
-
返回第一个错误是因为图像形状有3个分量,高度宽度和通道,第三个描述颜色分量的数量。您正在创建的“图像”没有第三种形状,因此 cvtColor 将无法使用它。尝试使用 np.expand_dims 添加第三个组件
-
@VaibhavMehrotra 当我打印 image.shape 时,我传递给 cvtColor 的膨胀图像只有高度和宽度,那么当图像已经是灰度时,为什么 HoughLinesP 会产生错误?
-
@OcheGeorge 检查变量的数据类型。
标签: python image opencv image-processing error-handling