[Solved] How to I extract objects? [closed]


First load the img from the url

import numpy as np
import urllib.request
from PIL import Image
from matplotlib import pyplot as plt

urllib.request.urlretrieve(
  'https://i.stack.imgur.com/GRHzg.png',
   "img.png")
img = Image.open("img.png")
img.show()

enter image description here

Then consider the black part as “filled” and convert in numpy array

arr = (np.array(img)[:,:,:-1].sum(axis=-1)==0)

If we sum the rows values for each column we can have a simple sum of how much pixel are filled in each column:

plt.subplot(211)
plt.imshow(arr, aspect="auto")
plt.subplot(212)
plt.plot(arr.sum(axis=0))
plt.xlim(0,arr.shape[1])

enter image description here

finally if we compute the differential of this sum over the columns we can obtain the following result:

plt.subplot(211)
plt.imshow(arr, aspect="auto")
plt.subplot(212)
plt.plot(np.diff(arr.sum(axis=0)))
plt.xlim(0,arr.shape[1])

enter image description here

At this point you can simply chose a threshold and cut the image:

threshold = 25
cut = np.abs(np.diff(arr.sum(axis=0)))>threshold
x_lines = np.arange(len(cut))[cut]

plt.imshow(arr, aspect="auto")
plt.vlines(x_lines, 0, arr.shape[0], color="r")

enter image description here

This is my solution and it works fine, but it is sensitive to the chosen threshold and to the columns gradient. I hope it is useful.

7

solved How to I extract objects? [closed]