【问题标题】:Converting RGBA Images in a folder and save it to another folder in '.pgm' format转换文件夹中的 RGBA 图像并将其以“.pgm”格式保存到另一个文件夹
【发布时间】:2016-02-12 05:52:50
【问题描述】:

我有一组RGBA图像保存在一个文件夹中,我的目标是将这些图像以pgm格式转换到另一个文件夹中,下面是代码:

path1 = file/path/where/image/are/stored
path2 = file/path/where/pgm/images/will/be/saved

list = os.listdir(path1)
for file in listing:
    #Transforms an RGBA with channel into an RGB only
    image_rgb = Image.open(file).convert('RGB')

    #Color separation stains to detect microscopic cells
    ihc_hed = rgb2hed(image_rgb)

    #Trasnforms the image into a numpy array of the UINT8 Type
    cv_img = ihc_hed.astype(np.uint8)

    # create color boundaries boundaries detecting black and blue stains
    lower = np.array([0,0,0], dtype = "uint8")
    upper = np.array([0,0,255], dtype = "uint8")
    #calculates the pixel within the specified boundaries and create a mask
    mask = cv2.inRange(cv_img, lower, upper)
    img = Image.fromarray(mask,'L')
    img.save(path2+file,'pgm')

但是我收到一条错误消息,指出 KeyError: 'PGM',似乎 'pgm' 格式不在模式中

感谢您的建议:)

【问题讨论】:

    标签: python image-processing scikit-image pgm


    【解决方案1】:

    据我所知,scikit image 使用 Python Imaging Library 插件来保存图像文件。 PIL 不支持 PGM。

    请参阅http://effbot.org/imagingbook/decoder.htm,了解如何编写自己的 PIL 文件解码器。

    摘录:

    import Image, ImageFile
    import string
    
    class SpamImageFile(ImageFile.ImageFile):
    
        format = "SPAM"
        format_description = "Spam raster image"
    
        def _open(self):
    
            # check header
            header = self.fp.read(128)
            if header[:4] != "SPAM":
                raise SyntaxError, "not a SPAM file"
    
            header = string.split(header)
    
            # size in pixels (width, height)
            self.size = int(header[1]), int(header[2])
    
            # mode setting
            bits = int(header[3])
            if bits == 1:
                self.mode = "1"
            elif bits == 8:
                self.mode = "L"
            elif bits == 24:
                self.mode = "RGB"
            else:
                raise SyntaxError, "unknown number of bits"
    
            # data descriptor
            self.tile = [
                ("raw", (0, 0) + self.size, 128, (self.mode, 0, 1))
            ]
    
    Image.register_open("SPAM", SpamImageFile)
    
    Image.register_extension("SPAM", ".spam")
    Image.register_extension("SPAM", ".spa") # dos version
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-05
      相关资源
      最近更新 更多