【发布时间】:2017-07-09 20:56:44
【问题描述】:
我对 OpenCV 世界很陌生。我正在开发一个项目,该项目需要(目前)检测图像中的数字,选择它们并保存。
这是我使用的代码:
# Importing modules
import cv2
import numpy as np
# Read the input image
im = cv2.imread('C:\\Users\\User\\Desktop\\test.png')
# Convert to grayscale and apply Gaussian filtering
im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
im_gray = cv2.GaussianBlur(im_gray, (5, 5), 0)
# Threshold the image
ret, im_th = cv2.threshold(im_gray, 90, 255, cv2.THRESH_BINARY_INV)
# Find contours in the image
image, ctrs, hier = cv2.findContours(im_th.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Bounding rectangle for a set of points
i = 0
#rects = [cv2.boundingRect(ctr) for ctr in ctrs]
#rects.sort()
for ctr in ctrs:
x, y, w, h = cv2.boundingRect(ctrs[i])
# Getting ROI
roi = im[y:y+h, x:x+w]
#cv2.imshow('roi',roi)
#cv2.waitKey()
i += 1
cv2.imwrite('C:\\Users\\User\\Desktop\\crop\\' + str(i) + '.jpg', roi)
#print(rects)
print("OK - NO ERRORS")
它工作了一半。问题是输出数字(在图像格式中,必须这样)不是按原始图像排序的(如下)。
这是输出:
代码有什么问题?
另外,您可以注意rects 变量。我用它来做一些调试,我注意到一个有趣的事情:如果我对它的内容进行排序,在控制台中图像数组的顺序是正确的。
有没有办法按原始顺序对图像进行排序?
我也看到了这个very similar post,但我无法理解解决方案。
非常感谢。
【问题讨论】: