从NumPy数组中删除值对

时间:2017-02-19 15:28:03

标签: 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)删除任何项目,但我一直收到这个错误: 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。我想忽略外围&#34;噪音&#34;用于文本选择。假设我无法进一步降低噪音。

1 个答案:

答案 0 :(得分:2)

看来contours.shape是(N,1,2)。在这种情况下,

def setAI(difficulty):  #difficulty='EASY' or 'HARD' or...e.t.c)
    configFile=open('AISettings.txt')
    config=configFile.readlines()
    for line in config:
        if line.startswith(difficulty.upper()):
             print(line[len(difficulty) + 1:])

会奏效。

通过示例:

h1.merge(h2) { |k,o,n| puts "#{k}=>#{o}" if o == n }
"b" => 2

如果您想在X和Y上使用不同的剪辑,则可以使用

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

代替。