【发布时间】:2019-11-13 04:00:48
【问题描述】:
我想要实现的是计算 cv2.drawContours 的边界框。 以前我尝试过许多解决方案,例如 CV_RETR_EXTERNAL 来检索外部轮廓,我一直试图实现的是一个简单的字数(不是字母数)。使用仅计算轮廓的逻辑,我可以实现字数统计。但问题在于计算countour边界框的代码。
import cv2
from matplotlib import pyplot as pt
test1 = cv2.imread("test5.png") # Read image
gray = cv2.cvtColor(test1, cv2.COLOR_BGR2GRAY) # Convert the image to grayscale
blur = cv2.GaussianBlur(gray,(3,3),0) # Apply Gaussian to reduce noise
# Apply threshold to extract the words from the image
threshold=cv2.adaptiveThreshold(blur,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY_INV,15,15)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (6,6)) # Create a structure element
dilate = cv2.dilate(threshold, kernel, iterations = 1) # Apply dilation to the image
contour, _ = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contour = cv2.drawContours(test1, contour, -1, (0, 255, 0), 3)
pt.figure()
pt.imshow(threshold, cmap="gray")
pt.title("Threshold")
pt.figure()
pt.imshow(dilate, cmap="gray")
pt.title("Dilate")
pt.figure()
pt.imshow(test1, cmap="gray")
pt.title("Contour")
i = np.array((),dtype=np.uint8)
for i in range(contour):
i += contour
print(i)
收到的错误是 TypeError:只有整数标量数组可以转换为标量索引。我还是编码新手,这是一个具有挑战性的问题。
【问题讨论】:
-
“收到的错误是...” 错误出现在哪里?另外,最后一个
for循环是为了什么? -
最后一个循环是根据边界框计算单词的数量。我的逻辑是定义的轮廓链接到 cv2.drawContours,因此如果每个 cv2.drawContours 是一个边界框,我可以计算单词的数量。
-
我猜它没有运行是因为程序出错并首先崩溃?将
i用于数组,然后立即用于循环计数器是一个坏主意,我真的建议更改它。我觉得这个循环很奇怪,我很好奇它会输出什么。 -
如果你能分享你正在使用的测试图像也很好。请参阅:minimal reproducible example。
-
我已经添加了图片,我会在练习代码的同时尝试测试代码并搜索示例。
标签: python opencv image-processing anaconda