Cut Colour Out of Picture

Viewed 34

I have pictures that present with black bars above and below the image:

enter image description here

The black bars are at a different height in the picture at different pictures. I want to remove the black bars from each picture and save a new picture to a folder. I googled a bit and found the following code (adapted for my needs).

Now, the problem is that the saved image still has the black bars. When I use getpixel to return the RGB value, it returns it as 0,0,0. Does anyone have any ideas?

from PIL import Image, ImageOps
from os import listdir
from os.path import isfile, join
import numpy

mypath_cut = "Redacted Path to Image"
onlyfiles_cut = [f for f in listdir(mypath_cut) if isfile(join(mypath_cut, f))]

StimulusNumber = 0 
for image in onlyfiles_cut:
    im = Image.open('Cow Pictures/Cut Pictures/{}'.format(image)).convert('RGB')
    na = numpy.array(im)
    
    blackY, blackX = numpy.where(numpy.all(na==[0,0,0], axis = 2))
    
    top, bottom = blackY[0], blackY[-1]
    left, right = blackX[0], blackX[-1]
    
    ROI = na[top:bottom, left:right]
    
    StimulusNumber += 1
    Image.fromarray(ROI).save("Cow Pictures/Cut Pictures/Cut_NoBlack/Cow{}.jpg".format(StimulusNumber))```

1 Answers

This code may help you out.

import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
image = np.array(Image.open("/Users/sohaibanwaartempr/Desktop/MCSTb.png").convert('RGB'))

# Mask of non-black pixels (assuming image has a single channel).
mask = image > 0

# Coordinates of non-black pixels.
coords = np.argwhere(mask)

# Bounding box of non-black pixels.
x0, y0, z0 = coords.min(axis=0)
x1, y1, z1 = coords.max(axis=0) + 1   # slices are exclusive at the top

# Get the contents of the bounding box.
cropped = image[x0:x1, y0:y1]
plt.imshow(cropped)
plt.show()
# crop_image(np.asarray(im),tol=0)

Cow

Related