【发布时间】:2017-02-19 15:28:02
【问题描述】:
我有一个 NumPy 数组 contours,我从 cv2.findContours 获得并使用 contours = np.concatenate(contours, axis = 0) 进行展平。它存储图像中对象轮廓的坐标。但是,我想删除 X 或 Y 小于 100 或大于 1000 的坐标。我首先尝试使用 contours = np.delete(contours, 0) 和 contours = np.delete(contours[0], 0) 删除任何项目,但我一直收到此错误:
IndexError: invalid index to scalar variable.
如何删除这样的值对?
print(type(contours))
→ <class 'numpy.ndarray'>
print(contours[0])
→ [[2834 4562]]
print(type(contours[0]))
→ <class 'numpy.ndarray'>
print(contours[0][0])
→ [2834 4562]
print(type(contours[0][0]))
<class 'numpy.ndarray'>
另外,我不想进一步连接/展平列表,因为它正是我需要发送到cv2.convexHull(contours) 的形式。
这是我的代码的最小工作示例:
import cv2 # library for processing images
import numpy as np # numerical calculcations for Python
img = cv2.imread("img.png")
img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
_, img_thr = cv2.threshold(img_gray,0,255,cv2.THRESH_OTSU)
img_rev = cv2.bitwise_not(img_thr)
img_cnt, contours, hierarchy = cv2.findContours(img_rev, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contours = np.concatenate(contours, axis = 0)
hull = cv2.convexHull(contours)
rect = cv2.minAreaRect(np.int0(hull))
box = cv2.boxPoints(rect)
box = np.int0(box)
img_cnt = cv2.drawContours(img, contours, -1, (0,255,0), 3)
img_cnt = cv2.drawContours(img, [box], -1, (0,0,255), 5)
cv2.imwrite("img_out.png", img_cnt)
这是一个示例input image,这是我的output image。我想忽略文本选择的外围“噪音”。假设我不能使用进一步的降噪。
【问题讨论】:
-
请创建一个Minimal, Complete, and Verifiable 示例。这让我们更容易为您提供帮助。
标签: python arrays opencv numpy