2017-07-09 59 views
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") 

它的工作原理半。问题是输出数字(图像格式,它需要这样)不是由原始图像(下面)排序。

Original test image

这是输出:

wrong output

什么是错误的代码?

此外,您可以注意rects变量。我用它来做一些调试,并且我注意到一件有趣的事情:如果我对它的内容进行排序,在控制台中,图像顺序阵列是正确的。

sorted array

有没有办法在原来的顺序对图像进行排序?

我也看到了这very similar post但我不明白的解决方案。

非常感谢。

回答

1

鉴于投资回报率可能在二维空间中分布,因此没有自然顺序。

如果您想通过x坐标,你可以做些什么来命令他们:

sorted_ctrs = sorted(ctrs, key=lambda ctr: cv2.boundingRect(ctr)[0]) 

,然后遍历sorted_ctrs而不是ctrs

编辑:更准确地说:

import cv2 
import numpy as np 

# Read the input image 
im = cv2.imread('JnUpW.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) 

# Sort the bounding boxes 
sorted_ctrs = sorted(ctrs, key=lambda ctr: cv2.boundingRect(ctr)[0]) 

for i, ctr in enumerate(sorted_ctrs): 
    # Get bounding box 
    x, y, w, h = cv2.boundingRect(ctr) 

    # Getting ROI 
    roi = im[y:y+h, x:x+w] 

    # Write to disk 
    cv2.imwrite(str(i) + '.jpg', roi) 

#print(rects) 
print("OK - NO ERRORS") 
+0

谢谢你的答案。我在i = 0计数器后插入你的代码并放入sorted_ctrs,但输出仍然相同。图像不是很好。 – BlueTrack

+0

它的工作原理。非常感谢。 – BlueTrack

+0

现在,只需要知道,这个排序过程依赖于什么?我的意思是,它是如何完成的?谁决定先拿5号而不是从1号开始? – BlueTrack