python - 在 ROI 之后对图像进行排序(Python、OpenCV)

标签 python sorting opencv roi

我几乎是 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但我无法理解解决方案。

非常感谢。

最佳答案

鉴于 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")

关于python - 在 ROI 之后对图像进行排序(Python、OpenCV),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45000939/

相关文章:

python - Scipy io 读取 wavfile 错误

python - 扭曲,ProcessProtocol 如何接收没有缓冲的标准输出?

python - 跨项目的 Cython 定义?

opencv - OpenCV 中的伪彩色滤镜

python - 如何将 .ipynb 文件上传到笔记本云实例?

javascript - 按属性对 JavaScript 对象数组进行排序时数字有什么问题

c - 使用指针: program that sorts an integer array,段错误

sorting - 如何让 Emacs 按长度对行进行排序?

image-processing - 使用 OpenCV 查找图像中矩形的位置

Python 和 OpenCV - 视频中的对象检测和替换