PIL 图像转换为 RGB,保存为纯黑色图像 (python)

use*_*627 3 python jpeg numpy image-processing

我想在剪切和编辑图像后将其保存为 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")
Run Code Online (Sandbox Code Playgroud)

但实际发生的情况是,所有图像都只是黑色。这是怎么回事?

mrc*_*rcl 8

您的图像mymyimage从 0 到 1,并且PIL期望图像的值在 0 到 255 之间。在截断期间,您的 jpeg 图像将具有截断值 0 或 1,从而导致黑色。

要解决这个问题,只需乘以mymyimg255,例如

outputimg = Image.fromarray(mymyimg*255)
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你。

干杯