1

I am trying to crop an image (cropping the background out of a school picture) using matplotlib, os.path, and numpy.

My idea was to section the image off into squares other than the part I needed and then manipulate the alpha channel to make those areas transparent so all I was left with was the part I needed. I have a start to the code but got stuck on the same error message.

I've tried to make some kind of circle mask to crop the face out but the concept of a mask is still foreign to me so I figured this would be easier.

fig, ax = plt.subplots(1, 1)
# Show the image data in a subplot
ax.imshow(img, interpolation='none')
# Show the figure on the screen

row = len(img)
column = len(img[0])
for row in range(0, 231) :
    for column in range(0, 330) :
        img[row][column] = [0, 0, 0, 0]


fig.show()

 

Results: 26 for row in range(0, 231) :
         27     for column in range(0, 330) :
    ---> 28         img[row][column] = [0, 0, 0]
         29 
         30 
IndexError: index 288 is out of bounds for axis 0 with size 288
Blaztix
  • 1,223
  • 1
  • 19
  • 28
omegalul
  • 37
  • 1
  • 4
  • Are you sure that you want to do this in matplotlib. I think there would be better tools available for the job. For instance, have a look at [this](https://stackoverflow.com/questions/20361444/cropping-an-image-with-python-pillow). – Thomas Kühn Feb 11 '19 at 14:55

1 Answers1

0

You would find that much easier with PIL/Pillow. Starting with this image of Fiona...

enter image description here

#!/usr/bin/env python3

from PIL import Image, ImageDraw

# Load image and get width and height
im = Image.open('fiona.png').convert('RGB')
w, h = im.size[0:2]

# Make empty black alpha mask same size, but with just one channel, not RGB
alpha = Image.new('L',(w,h))

# Draw white ellipse in mask - everywhere we paint white the original image will show through, everywhere black will be masked
draw = ImageDraw.Draw(alpha)
draw.ellipse([80,100,210,210],fill=255) 

# Add alpha mask to image and save
im.putalpha(alpha)
im.save('result.png')

enter image description here

Here is the alpha mask we created:

enter image description here

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432