灰度图像不是jpeg

2024-07-03 06:16:00 发布

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

我创建了一个像这样的灰度图像

def create_new_image(size, luminance):
    width, height = size
    black_frame = int(luminance) * np.ones((width, height, 1), dtype=np.uint8)
    return black_frame

其中亮度是[0255]的元素

我已使用imageio保存图像

def save_image(image, output_path):
    imageio.imwrite(output_path, image)

其中output_path类似于/valid_path/img.jpg

现在我想重新加载我的灰度图像:

img = imageio.imread(file, format ='jpg')

但我得到的是一个语法错误

raise SyntaxError("not a JPEG file")
  File "<string>", line None
SyntaxError: not a JPEG file

如果我没有指定格式,我会得到另一个错误

    "Could not find a format to read the specified file in %s mode" % modename
ValueError: Could not find a format to read the specified file in single-image mode

为什么?? 谢谢


Tags: path图像imageformatoutputsizedefnot
3条回答

JPEG文件(压缩图像)以始终包含标记代码十六进制值FF D8 FF的图像标记开始。它并没有嵌入文件的长度,所以我们需要找到JPEG拖车,它是FF D9

请使用位于this page的链接查看文档

例如,使用十六进制查看器(例如Hex Viewer)打开jpeg图像时,您应该会看到如下内容:

enter image description here

解决方案:换句话说,在将文件保存为JPEG之前,尝试将文件头添加到文件中,您应该可以解决问题

可以在here找到包含API文档的页面。在文档之后,您应该找到正确的指令,该指令使您指定保存格式(正如@Meto在回答中指出的)

结论:解决方案只是指定在硬盘中物理写入图像时的格式:

imageio.imwrite(uri, im, format=None, **kwargs)

在你的例子中format=jpg

而且

 imageio.show_formats()

显示格式良好的可用格式列表

最后,试着替换

imageio.imwrite(output_path, image)

imageio.imwrite(output_path, image, format ='jpg' )

请注意每个答案的解决方案总是相同的。我刚刚添加了指定格式时发生的事情(即,只写正确的标题)

您可以尝试:

def save_image(image, output_path):
    imageio.imwrite(output_path, format= "jpg", image)

明确声明它是一个jpg文件

您需要确保您的文件是否真的保存为JPG文件。 在Linux/Mac上,您可以使用file命令来验证这一点

例如,下面的命令确认fireside.jpg是JPEG文件:

# file fireside.jpg
fireside.jpg: JPEG image data, JFIF standard 1.01, aspect ratio, density 1x1, segment length 16, baseline, precision 8, 2048x1365, components 3

如果文件未另存为JPG,请尝试将file format=“JPG”指定为

imageio.imwrite(output_path, image, format ='jpg')

相关问题 更多 >