首页 > 解决方案 > Python将TIF格式的图像转换为PNG

问题描述

我正在运行下面的代码将文件从 tifs 转换为 PNG,但转换后的图像没有正确转换新文件被破坏,并且文件的一半中有行,如附件图像所示。知道为什么会发生这种情况吗?在此处输入图像描述.

import os
from PIL import Image

yourpath = os.getcwd()
for root, dirs, files in os.walk(yourpath, topdown=False):
    for name in files:
        print(os.path.join(root, name))
        if os.path.splitext(os.path.join(root, name))[1].lower() == ".tif":
            if os.path.isfile(os.path.splitext(os.path.join(root, name))[0] + ".png"):
                print ("A png file already exists for %s" % name)
            # If a PNG is *NOT* present, create one from the tiff.
            else:
                outfile = os.path.splitext(os.path.join(root, name))[0] + ".png"
                try:
                    im = Image.open(os.path.join(root, name))
                    print("Generating jpeg for %s" % name)
                    im.thumbnail(im.size)
                    im.save(outfile, "png", quality=100)
                except Exception as e:
                    print (e)

运行 tiffinfo 提供以下详细信息:

TIFF Directory at offset 0x8 (8)
  Image Width: 1024 Image Length: 1024
  Resolution: 5000, 5000 pixels/cm
  Bits/Sample: 8
  Sample Format: unsigned integer
  Compression Scheme: LZW
  Photometric Interpretation: RGB color
  Samples/Pixel: 3
  Rows/Strip: 1
  Planar Configuration: separate image planes
  ImageDescription: <?xml version="1.0" encoding="UTF-8"?><!-- Warning: this comment is an OME-XML metadata block, which contains crucial dimensional parameters and other important metadata. Please edit cautiously (if at all), and back up the original data before doing so. For more information, see the OME-TIFF web site: https://docs.openmicroscopy.org/latest/ome-model/ome-tiff/. --><OME xmlns="http://www.openmicroscopy.org/Schemas/OME/2016-06" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Creator="OME Bio-Formats 5.9.2" UUID="urn:uuid:5d7dfdcc-e0e9-4899-9aa2-64717b405232" xsi:schemaLocation="http://www.openmicroscopy.org/Schemas/OME/2016-06 http://www.openmicroscopy.org/Schemas/OME/2016-06/ome.xsd"><Image ID="Image:0" Name="p1_Bromophenol_1mM - Mark_and_Find 001/Position026 (RGB rendering)"><Pixels BigEndian="true" DimensionOrder="XYCZT" ID="Pixels:0" PhysicalSizeX="2.0" PhysicalSizeXUnit="┬Ám" PhysicalSizeY="2.0" PhysicalSizeYUnit="┬Ám" PhysicalSizeZ="1.0" PhysicalSizeZUnit="┬Ám" SizeC="3" SizeT="1" SizeX="1024" SizeY="1024" SizeZ="1" TimeIncrement="1.0" TimeIncrementUnit="s" Type="uint8"><Channel ID="Channel:0:0" Name="red" SamplesPerPixel="3"><LightPath/></Channel><TiffData FirstC="0" FirstT="0" FirstZ="0" IFD="0" PlaneCount="1"><UUID FileName="Position026 (RGB rendering) - 1024 x 1024 x 1 x 1 - 3 ch (8 bits).tif">urn:uuid:5d7dfdcc-e0e9-4899-9aa2-64717b405232</UUID></TiffData></Pixels></Image></OME>
  Software: OME Bio-Formats 5.9.2

标签: python-3.ximageimage-processingpython-imaging-librarytiff

解决方案


推荐阅读