如何基于Python OpenCV的空白区域或边缘检测将图像分割成多个小图像?

Luc*_* Lu 1 python opencv image image-processing computer-vision

图片在这里

我有很多类似的图片。由于是手写体,因此每个文本/罗马数字的大小可能会有所不同。

如何保存每个文本/罗马数字以.png单独格式化?有 9 个文本,其中一个点。所以输出应该分别是 10 或 9 个图像。每个文本/罗马数字之间的空格不同。我应该根据精明的边缘或任何更好的方法来裁剪它们吗?

我不确定这有多难,因为我是简历的初学者。但我计划为我的项目这样做。

nat*_*ncy 6

主要思想是使用膨胀将各个轮廓组合在一起,然后单独裁剪每个轮廓。这是一个简单的方法

  1. 获取二值图像。 加载图像灰度高斯模糊大津阈值,然后膨胀以获得二值黑白图像。

  2. 提取投资回报率。 查找轮廓获取边界框,使用Numpy切片提取ROI,并保存每个ROI


检测到的 ROI 以绿色突出显示

提取并保存 ROI

import cv2

# Load image, grayscale, Gaussian blur, Otsu's threshold, dilate
image = cv2.imread('1.jpg')
original = image.copy()
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (15,15))
dilate = cv2.dilate(thresh, kernel, iterations=2)

# Find contours, obtain bounding box coordinates, and extract ROI
cnts = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
image_number = 0
for c in cnts:
    x,y,w,h = cv2.boundingRect(c)
    cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 3)
    ROI = original[y:y+h, x:x+w]
    cv2.imwrite("ROI_{}.png".format(image_number), ROI)
    image_number += 1

cv2.imshow('image', image)
cv2.imshow('thresh', thresh)
cv2.imshow('dilate', dilate)
cv2.waitKey() 
Run Code Online (Sandbox Code Playgroud)