0

I have some python code that takes in an image of an A4 letter, then draws bounding boxes around each character.

I want to know how to save each bounding box as an image, so essentially it's taking every character it detects and saving it. Preferable as a .png resized to 20x20

(A similar question was asked here but the answer is quite vague and don't know how to implement it in my code)

Here is my code:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from scipy.misc import imread,imresize
from skimage.segmentation import clear_border
from skimage.morphology import label
from skimage.measure import regionprops


image = imread('./adobe.png',1)

#apply threshold in order to make the image binary
bw = image < 120

# remove artifacts connected to image border
cleared = bw.copy()
clear_border(cleared)

# label image regions
label_image = label(cleared,neighbors=8)
borders = np.logical_xor(bw, cleared)
label_image[borders] = -1

print label_image.max()

fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(6, 6))
ax.imshow(bw, cmap='jet')



for region in regionprops(label_image, ['Area', 'BoundingBox']):
    # skip small images
    if region['Area'] > 50:

        # draw rectangle around segmented coins
        minr, minc, maxr, maxc = region['BoundingBox']
        rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr,
                              fill=False, edgecolor='red', linewidth=2)
        ax.add_patch(rect)

plt.show()

If I'm not clear enough, please comment and I'll try elaborate my best,

Thank you

Community
  • 1
  • 1
Zack
  • 1
  • 1
  • 2

1 Answers1

3

The question you reference uses findContours from OpenCV, a common library for image manipulation. If you already have the bounding box (in x, y and width, height) then you can simply export using matplotlib or, alternatively opencv:

image_patch = img[minr:maxr, minc:maxc]  # get region of interest (slice)
# .. maybe do some scaling
plt.imsave("filename.png", image_patch)

Alternatively with fig.savefig(path) after rendering it to a figure. Or with opencv:

import cv2
cv2.imsave("path.png", img_patch)

You may want to add suffixes to your file names (and/o checking if the file already exists?) to avoid overwriting.

user3736966
  • 111
  • 1
  • 2
  • Hi there thanks for your answer, I've put the two first lines of code you suggested in my for loop, it now does save images however the area that it saves is kind of wrong. I get a few letters saved but also a lot of partial and just blank spaces saved. I think your code is right but I don't know how to get the exact boundries converted to the format [minc:maxc, minr:maxr], any suggestions? – Zack May 01 '16 at 19:23
  • sorry, of course its rows, then columns. i fixed it in the example. If you can provide a suitable test image i can test it (provided your code snippet is complete). – user3736966 May 02 '16 at 13:12