使用Python图像库将

如何解决使用Python图像库将

我创建了一个批处理作业,该作业在文件夹中打开.TIFF文件,调整它们的大小,将它们转换为.PNG文件,然后将它们保存在其他文件夹中。批处理作业运行正常并且图片得到正确处理,但是在某些特定图片(可以将其作为普通的.TIFF文件打开)中,该过程停止并显示以下错误日志:

    ---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
<ipython-input-3-499452368347> in <module>
     47                 target_size = (target_x,target_y)
     48                 print("Image gets converted from size " + str(img_size) + " to " + str(target_size))
---> 49                 resized_image = image.resize(target_size,Image.BICUBIC)
     50 
     51                 # Save the image as a PNG to the target_dir

C:\EigeneProgramme\Python38-64\lib\site-packages\PIL\Image.py in resize(self,size,resample,box,reducing_gap)
   1897 
   1898         if self.mode in ["LA","RGBA"]:
-> 1899             im = self.convert(self.mode[:-1] + "a")
   1900             im = im.resize(size,box)
   1901             return im.convert(self.mode)

C:\EigeneProgramme\Python38-64\lib\site-packages\PIL\Image.py in convert(self,mode,matrix,dither,palette,colors)
    891         """
    892 
--> 893         self.load()
    894 
    895         if not mode and self.mode == "P":

C:\EigeneProgramme\Python38-64\lib\site-packages\PIL\TiffImagePlugin.py in load(self)
   1085     def load(self):
   1086         if self.tile and self.use_load_libtiff:
-> 1087             return self._load_libtiff()
   1088         return super().load()
   1089 

C:\EigeneProgramme\Python38-64\lib\site-packages\PIL\TiffImagePlugin.py in _load_libtiff(self)
   1189 
   1190         if err < 0:
-> 1191             raise OSError(err)
   1192 
   1193         return Image.Image.load(self)

OSError: -2

此错误实际上不是很容易解释,我在网上找不到合适的解决方案。有人可以帮忙吗?

这是完整的(相关)代码:

 from PIL import Image
import os

# The directory which should be converted
source_dir = './Edge_Bands_Scan_Sorted/'
# The directory to which the converted files should be stored
target_dir = './Edge_Bands_Scan_Sorted_PNGs/'

# Create the target dir,if it does not exist already
if not os.path.exists(target_dir):
    os.makedirs(target_dir)

count = 0
valid = 0
# Iterate through all the files in the source_dir-directory
for subdir,dirs,files in os.walk(source_dir):
    for file in files:
        # Check if file is a TIFF-File:
        #if(file[-5:] == '.tiff' or file[-5:] == '.TIFF' ):
        if file.lower().endswith(".tiff"):
            file_path = os.path.join(subdir,file)
            #Print list of all files
                #print(file_path)
            # Extract edge band pattern name from the filepath
            # Get postion of last backslash and only get the text after this backslash
            last_backslash_position = file_path.rfind("\\")
            after_last_backslash = file_path[last_backslash_position + 1:]
            # Remove file ending
            after_last_backslash_without_ending = after_last_backslash[:-5]
            # Only the text before the first underscore is the REHAU Color Code
            first_underscore_position = after_last_backslash_without_ending.find("_")
            color_code = after_last_backslash_without_ending[:first_underscore_position]

            # open the files to write
            file = open(list_path,'a')
            error_file = open(error_list_path,'a')

            # Check if the colorcode is already converted
            if not color_code in converted_color_codes_list:
                try:
                    # Process the image
                    print("Loading image [{}] {}".format(count,file_path))
                    # Use PIl to load the image - there are problems with some images
                    image = Image.open(file_path)
                    # Get the image size
                    img_size = image.size
                    img_x = image.size[0]
                    img_y = image.size[1]

                    # Target width of the image
                    target_x = 1000
                    target_y = int(img_y * target_x / img_x)
                    target_size = (target_x,target_y)
                    print("Image [{}] gets converted from size {} to {} ".format( count,str(img_size),str(target_size)))
                    resized_image = image.resize(target_size,Image.BICUBIC)

                    # Save the image as a PNG to the target_dir
                    new_path = target_dir + color_code + '.png'
                    print("The converted image [{}]  gets saved to path {}".format( count,new_path))
                    resized_image.save(new_path,"PNG",optimize=True,compress_level=6)
                    
                    # If successful,add the color code to the list
                    # First add a new line
                    if existing_list:
                        file.write("\n")
                    # Then add the color code
                    file.write(color_code)
                    existing_list = True
                    valid += 1
                except OSError:
                    print("ERROR: Image [{}] at path {} could not be processed".format (count,file_path))
                    # If there occurs an error while processing,save the image name and path to the file
                    if existing_error_list:
                        error_file.write("\n")
                    # Then add the color code
                    error_file.write(color_code + " - " + file_path)
                    existing_error_list = True
            else:
                #Handle duplicate files 
                print("DUPLICATE: Image [{}] at path {} with color code {} is already converted".format(count,file_path,color_code))     

            count += 1
            # Close the file access again
            error_file.close()
            file.close()

        else:
            #Ignore other filetypes
            break
print("{}/{} were successfully converted".format(valid,count))

该文件夹在嵌套子目录系统中包含约2100个.tiff图像。其中149个未得到正确处理,但另一个得到了罚款。我发现正确处理的图片与导致错误的图片之间没有任何区别。

这是正确处理图片的示例路径: ./Edge_Bands_Scan_Sorted/Wooden\TIFF\W_E_B_NG\1475B_W_E_B_NG.TIFF

这是未正确处理图片的示例路径:./Edge_Bands_Scan_Sorted/Wooden\TIFF\W_E_B_NG\3200B_W_E_B_NG.TIFF

解决方法

我完全不确定这是怎么回事。我认为,但不能完全确定,问题在于该文件每个像素有4个样本(即RGBA),但是“ Sample Format” 标签仅给出3种类型(即无符号整数)四个样本中的一个,这使该库不堪一击。

以下是tiffdump输出,其中突出显示了矛盾的字段:

tiffdump 3200B_W_E_B_NG.TIFF 
3200B_W_E_B_NG.TIFF:
Magic: 0x4949 <little-endian> Version: 0x2a <ClassicTIFF>
Directory 0: offset 9441002 (0x900eea) next 0 (0)
SubFileType (254) LONG (4) 1<0>
ImageWidth (256) LONG (4) 1<5477>
ImageLength (257) LONG (4) 1<1248>
BitsPerSample (258) SHORT (3) 4<8 8 8 8>
Compression (259) SHORT (3) 1<5>
Photometric (262) SHORT (3) 1<2>
StripOffsets (273) LONG (4) 1248<8 7558 15109 22684 30223 37769 45253 52740 60181 67699 75210 82702 90231 97784 105221 112698 120165 127581 135073 142615 150195 157794 165402 173003 ...>
Orientation (274) SHORT (3) 1<1>
SamplesPerPixel (277) SHORT (3) 1<4>           <--- 4 SAMPLES PER PIXEL
RowsPerStrip (278) LONG (4) 1<1>
StripByteCounts (279) LONG (4) 1248<7550 7551 7575 7539 7546 7484 7487 7441 7518 7511 7492 7529 7553 7437 7477 7467 7416 7492 7542 7580 7599 7608 7601 7565 ...>
XResolution (282) RATIONAL (5) 1<1600>
YResolution (283) RATIONAL (5) 1<1600>
PlanarConfig (284) SHORT (3) 1<1>
ResolutionUnit (296) SHORT (3) 1<2>
Predictor (317) SHORT (3) 1<2>
ExtraSamples (338) SHORT (3) 1<2>
SampleFormat (339) SHORT (3) 3<1 1 1>          <--- ONLY THREE FORMATS BUT 4 SAMPLES

作为一种解决方法,似乎tifffile可以打开“不满意” 图片,因此您可以使用:

from tifffile import imread

# Open with "tifffile"
img = imread('3200B_W_E_B_NG.TIFF')

# Make into "PIL Image" and carry on as usual
pi = Image.fromarray(img)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-