Skip to content
Advertisement

Python split image into multiple pieces by horizontal dashed lines

I have a bunch of image like this one:

enter image description here

Where the yellow box are contents of different profiles (text), where each section is divided by the dashed lines (no the straight lines). So what I need is to split the image into multiple single images by the dashed lines. So far I have tried a lot of python and cv2 examples with the Hough Line Transform but none of my attempts works in the detection.

Advertisement

Answer

Following @efirvida’s comment, here’s a very basic approach on how to do it.

What it does is simply checking whether each line of pixels in the given picture is equal in value to the first line containing a dashed line, and then crop the picture to split it into multiple pictures…

# 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)

It quite certainly isn’t a perfect solution but I hope it gives you clues on how to improve your current algorithm!

It gave me these pictures for the one you provided:

  • first split

enter image description here

  • second split

enter image description here

  • third split

enter image description here

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement