【问题标题】:Sort images after ROI (Python, OpenCV)在 ROI 之后对图像进行排序(Python、OpenCV)
【发布时间】: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,但我无法理解解决方案。

非常感谢。

【问题讨论】:

    标签: python sorting opencv roi


    【解决方案1】:

    鉴于 ROI 可以分布在二维空间中,因此没有自然顺序。

    如果您想按 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")
    

    【讨论】:

    • 感谢您的回答。我在 i=0 计数器之后插入了您的代码并放置了 sorted_ctrs 但输出仍然相同。图片排列不整齐。
    • 现在,只是想知道,这个排序过程取决于什么?我的意思是,它是如何完成的?谁决定先拿数字 5 而不是从 1 开始?
    • 好吧,如果您阅读文档:docs.opencv.org/2.4/modules/imgproc/doc/…,他们似乎根本不对订单做出任何保证。所以我假设它是一个实现细节,作为用户你应该假设它是随机的。
    猜你喜欢
    • 2013-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-20
    • 2020-08-31
    相关资源
    最近更新 更多