Python通过水平虚线将图像分割为多个部分

2024-04-18 21:36:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一堆像这样的图像:

enter image description here

其中,黄色框是不同配置文件(文本)的内容,其中每个部分由虚线分隔(不包括直线)。所以我需要的是用虚线将图像分割成多个单独的图像。到目前为止,我已经用Hough-Line变换尝试了很多python和cv2示例,但我的任何尝试都不能用于检测


Tags: 图像文本示例内容配置文件linecv2直线
1条回答
网友
1楼 · 发布于 2024-04-18 21:36:06

在@efirvida的评论之后,下面是一个非常基本的方法

它所做的只是检查给定图片中的每一行像素值是否等于包含虚线的第一行,然后裁剪图片以将其分割为多个图片

# import image/array manipulation packages
import cv2
import numpy as np

# read image with OpenCV 2
img = cv2.imread("path/to/file/z4Xje.jpg")

# identify one line of pixels that has dashes
dashes = img[761,:,:]

# check where to split the picture and store that information
splits = [0]
for i in range(img.shape[0]):
    # np.allclose allows you to have small differences between dashed lines
    if np.allclose(img[i,:,:], dashes):
        splits.append(i)

# add last split (height of picture)
splits.append(img.shape[0])

# write each cropped picture to your desired directory
for j in range(len(splits)-1):
    new_img = img[splits[j]:splits[j+1],:]
    cv2.imwrite("/path/to/export/"+str(j)+".jpg", new_img)

这当然不是一个完美的解决方案,但我希望它能为您提供如何改进当前算法的线索

它给了我这些你提供的照片:

  • 第一次分裂

enter image description here

  • 第二次分裂

enter image description here

  • 第三次分裂

enter image description here

相关问题 更多 >