2
我是OpenCV世界的新手。我正在研究一个需要(现在)检测图像中的数字的项目,选择它们并保存。ROI后对图像进行排序(Python,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但我不明白的解决方案。
非常感谢。
谢谢你的答案。我在i = 0计数器后插入你的代码并放入sorted_ctrs,但输出仍然相同。图像不是很好。 – BlueTrack
它的工作原理。非常感谢。 – BlueTrack
现在,只需要知道,这个排序过程依赖于什么?我的意思是,它是如何完成的?谁决定先拿5号而不是从1号开始? – BlueTrack