Python:无法将图像保存为灰色

2024-10-04 11:29:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这段代码,它成功地裁剪了我要保存的图像。 但是我也用一个.Convert(“LA”)打开图像,它应该确保图像是灰度的。我使用的是PIL库而不是matplotlib

然而,当我看到保存的图像时,它们的大小都是正确的,但其中一些仍然是彩色的。 我该怎么解决这个问题

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)

Tags: andto图像imagemessageconvertimgsize
2条回答

您正试图将图像保存到从中读取原始图像的相同filePath。我打赌有些图像在读取时会抛出异常,而您永远无法转换它们

您可以检查文件上的日期,对它们进行排序,您会发现彩色图像的创建日期/时间最早,因为它们没有被例程处理

convert('L')是好的,顺便说一句。你的问题是,它有时达不到那里

你的倒数第二行是 grayIm = croppedIm.convert("LA")

注意LA,你有LgrayIm = croppedIm.convert("L")

相关问题 更多 >