python - 从 NumPy 数组中删除值对

标签 python arrays opencv numpy

我有一个从 contours 获得的 NumPy 数组 cv2.findContours 并使用 contours = np.concatenate(contours, axis = 0) 进行扁平化。它存储图像中对象轮廓的坐标。但是,我想删除 X 或 Y 小于 100 或大于 1000 的坐标。我首先尝试使用 contours = np.delete(contours, 0)contours = np.delete(contours[0], 0) 来删除任何项目,但我不断收到此错误: ojit_代码

如何删除这样的值对?

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'>

此外,我不想进一步连接/展平列表,因为它正是我需要它发送到 IndexError: invalid index to scalar variable. 的形式。

这是我的代码的最小工作示例:

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 。我想忽略文本选择的外围“噪音”。假设我无法进一步降低噪音。

最佳答案

轮廓.shape 似乎是 (N,1,2) 。在这种情况下,

contours[((contours>100)&(contours<1000)).all(axis=(1,2))]

会起作用的。

举例:

In [106]: contours=randint(0,1100,(10,1,2))
[[[ 803  772]]
 [[ 210  490]]
 [[ 433   76]]
 [[ 347   88]]
 [[ 763  747]]
 [[ 678  200]]
 [[ 816  444]]
 [[ 528  817]]
 [[ 140  440]]
 [[1019  654]]]

In [108]: valid = ((contours>100)&(contours<1000)).all(axis=(1,2))
Out[108]: array([ True,  True, False, False,  True,  True,  
                  True,  True,  True, False], dtype=bool)

In [111]: contours[valid]
Out[111]: 
array([[[803, 772]],
       [[210, 490]],
       [[763, 747]],
       [[678, 200]],
       [[816, 444]],
       [[528, 817]],
       [[140, 440]]])

如果你想在 X 和 Y 上使用不同的剪辑,那么你可以使用

(contours>[xmin,ymin])&(contours<[xmax,ymax])

相反。

关于python - 从 NumPy 数组中删除值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42329056/

相关文章:

python - 为什么这段代码在不同的发行版/Unix 上表现不同?

python - Discord Python 机器人 : Changing Status

python - 当包含空格时解析新行分隔的字符串

javascript - 单击按钮时更改数组中的文本

OpenCV C2 类型的图像?

python - Python:OpenCV-选择图像区域

python - 多维 numpy 矩阵的旋转和翻转

c - 在 C 语言中,是否可以像在 char 数组声明中初始化字符串一样在指针声明中初始化字符串?

c - 将数组传递给另一个 C 函数是如何工作的?

c++ - 在 Visual C++ 中将 win32 .lib 与 x64 项目一起使用