PIL 图像转换为 RGB 格式后,以纯黑色图像保存(Python)。

3

我有一些图像需要在剪裁和编辑后以jpeg格式保存。

以下是我的Python函数:

import numpy as np
from skimage import data, io, filter, color, exposure
import skimage.transform as tf
from skimage.transform import resize, rescale, rotate, setup, warp, AffineTransform
import os
from os import listdir
from os.path import isfile, join
from PIL import Image


def generateHoGSamples(path, readfile):
    print "generating samples from  " + path+"\\"+readfile
    img = color.rgb2gray(io.imread(path+"\\"+readfile))
    img = resize(img, (50,100))
    filename = os.path.splitext(readfile)[0]
    angles = [3, 0, -3]
    shears = [0.13, 0.0, -0.13]
    imgidx = 0
    for myangle in angles:
        myimg = rotate(img, angle=myangle, order=2)
        for myshear in shears:
            imgidx+=1
            afine_tf = tf.AffineTransform(shear=myshear)
            mymyimg = tf.warp(myimg, afine_tf)
            outputimg = Image.fromarray(mymyimg)
            # Saving as "jpg" without the following line caused an error
            outputimg = outputimg.convert('RGB')
            outputimg.save(path+"//"+str(imgidx)+".jpg", "JPEG")

但实际上发生的是所有图像都是纯黑色的。 这是什么问题?
1个回答

8

您的图像mymyimage取值范围为0到1,而PIL期望图像的值在0到255之间。在截断过程中,您的JPEG图像将具有被截断的值0或1,从而导致变成黑色。

要解决这个问题,只需将mymyimg乘以255,例如:

outputimg = Image.fromarray(mymyimg*255)

希望对你有所帮助。
祝好。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接