0

I have this block of code which successfully crops the images I want to save. But I also open the images with a .Convert("LA") which should ensure the image is Greyscaled. I am using the PIL library and not matplotlib.

Yet when I look at the images saved, they are all the correct size but some of them are still showing in colour. How do I fix this?

def resizeImage(self, filePath):
    # [left, up, right, bottom] 
    img = Image.open(filePath).convert('LA')    # 'LA' set image to greyscale
    width, height = img.size
    print("-" * 100)
    message = f"Image Size = {width} x {height} image = {filePath}"
    print(message)
    croppedIm = img
    if width == 640 and height == 480:
        return img  # Image the correct size, so let through
    if width == 640 and height == 490:
        croppedIm = img.crop((0, 0, 640, 480))
    elif width == 720 and height == 480:
        croppedIm = img.crop((40, 0, 680, 480))
    else:
        try:
            raise Exception("Unexpected " + message)
        except Exception as inst:
            print(inst)          # __str__ allows args to be printed directly
            raise

    width, height = croppedIm.size
    print(f"Cropped Image Size = {width} x {height} image = {filePath}")
    print("-" * 100) 
    grayIm = croppedIm.convert("L")   
    return grayIm.save(filePath)
arame3333
  • 9,887
  • 26
  • 122
  • 205

2 Answers2

1

You're trying to save the images to the same filePath where you read your original images from. I bet some images just throw exception on read, and you never get to convert them.

You may check the dates on the files, sort them and you'll find out the color images have the oldest creation date/time, because they were NOT processed by your routine.

convert('L') is fine, BTW. Your problem that it sometimes do not get there.

lenik
  • 23,228
  • 4
  • 34
  • 43
  • I was taken by surprise that some colour images included in this "if " statement and were therefore not saved; if width == 640 and height == 480: return img . So I fixed that by saving the image there. – arame3333 Dec 26 '19 at 12:55
  • 1
    @arame3333 nice catch, I did not notice that, however the general thread was about similar behaviour – lenik Dec 27 '19 at 06:04
0

Should your second to last line be grayIm = croppedIm.convert("LA")

notice the LA, your have L, grayIm = croppedIm.convert("L")

Kenan
  • 13,156
  • 8
  • 43
  • 50