如何将RGB图像转换为NumPy数组?

160

我有一张 RGB 图像,想将其转换为 numpy 数组。我尝试了以下操作:

im = cv.LoadImage("abc.tiff")
a = numpy.asarray(im)

它创建了一个没有形状的数组。我猜它是一个IplImage对象。


2
如果cv是OpenCV模块,那么你应该将其标记为这样。这个链接可能会有所帮助:http://opencv.willowgarage.com/documentation/python/cookbook.html#numpy-and-opencv - Paul
15个回答

2

我也采用了imageio,但我发现以下机器对预处理和后处理很有帮助:

import imageio
import numpy as np

def imload(*a, **k):
    i = imageio.imread(*a, **k)
    i = i.transpose((1, 0, 2))  # x and y are mixed up for some reason...
    i = np.flip(i, 1)  # make coordinate system right-handed!!!!!!
    return i/255


def imsave(i, url, *a, **k):
    # Original order of arguments was counterintuitive. It should
    # read verbally "Save the image to the URL" — not "Save to the
    # URL the image."

    i = np.flip(i, 1)
    i = i.transpose((1, 0, 2))
    i *= 255

    i = i.round()
    i = np.maximum(i, 0)
    i = np.minimum(i, 255)

    i = np.asarray(i, dtype=np.uint8)

    imageio.imwrite(url, i, *a, **k)

我的理由是我使用numpy进行图像处理,而不仅仅是图像显示。为此,uint8类型的数据有些尴尬,因此我将其转换为从0到1的浮点值。

当保存图像时,我发现必须自己裁剪超出范围的值,否则最终输出会变得非常灰暗。(因为imageio压缩了整个超出[0,256)范围的值,并将其压缩为在此范围内的值,所以结果产生了灰色输出。)

还有其他一些奇怪的问题,这些问题我也在评论中提到了。


1
我们可以使用OpenCV2的以下函数将BGR格式转换为RGB格式。
RBG_Image = cv2.cvtColor(Image, cv.COLOR_BGR2RGB)

cv.COLOR_BGR2RGB 更改为 cv2.COLOR_BGR2RGB - Max Base

0
你可以尝试以下方法。这里是指向文档的链接。
tf.keras.preprocessing.image.img_to_array(img, data_format=None, dtype=None)
from PIL import Image
img_data = np.random.random(size=(100, 100, 3))
img = tf.keras.preprocessing.image.array_to_img(img_data)
array = tf.keras.preprocessing.image.img_to_array(img)

0

尝试计时选项以将图像加载到numpy数组中,它们非常相似。 为了简单和速度,请选择plt.imread

def time_this(function, times=100):
    cum_time = 0
    for t in range(times):
        st = time.time()
        function()
        cum_time += time.time() - st
    return cum_time / times

import matplotlib.pyplot as plt
def load_img_matplotlib(img_path):
    return plt.imread(img_path)

import cv2
def load_img_cv2(img_path):
    return cv2.cvtColor(cv2.imread(img_path), cv2.COLOR_BGR2RGB)

from PIL import Image
import numpy as np
def load_img_pil(img_path):
    img = Image.open(img_path)
    img.load()
    return np.asarray( img, dtype="int32" )

if __name__=='__main__':
    img_path = 'your_image_path'
    for load_fn in [load_img_pil, load_img_cv2, load_img_matplotlib]:
        print('-'*20)
        print(time_this(lambda: load_fn(img_path)), 10000)

结果:

--------------------
0.0065201687812805175 10000  PIL, as in [the second answer][1]https://dev59.com/smsz5IYBdhLWcg3wn5ba#7769424)
--------------------
0.0053211402893066405 10000  CV2
--------------------
0.005320906639099121 10000  matplotlib

0
使用 Keras:
from keras.preprocessing import image
  
img = image.load_img('path_to_image', target_size=(300, 300))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
images = np.vstack([x])

在我的情况下,它不能处理jpeg格式。建议使用PIL.Image。 - Michael Chao

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