在python中将图像转换为二维数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27026866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert an image to 2D array in python
提问by Sanket
I want to convert an image to 2D array with 5 columns where each row is of the form [r, g, b, x, y]. x, y is the position of the pixel and r,g,b are the pixel values. (I will be using this array as input to a machine learning model). Is there a more efficient implementation than this in python?
我想将图像转换为 5 列的二维数组,其中每行的形式为[r, g, b, x, y]。x, y 是像素的位置,r,g,b 是像素值。(我将使用这个数组作为机器学习模型的输入)。在python中有比这更有效的实现吗?
import Image
import numpy as np
im = Image.open("farm.jpg")
col,row = im.size
data = np.zeros((row*col, 5))
pixels = im.load()
for i in range(row):
for j in range(col):
r,g,b = pixels[i,j]
data[i*col + j,:] = r,g,b,i,j
采纳答案by YXD
I had to write this recently and ended up with
我最近不得不写这篇文章,结果是
indices = np.dstack(np.indices(im.shape[:2]))
data = np.concatenate((im, indices), axis=-1)
Where imis a numpy array. You are probably better off reading the images straight into numpy arrays with
imnumpy 数组在哪里。您可能最好将图像直接读取到 numpy 数组中
from scipy.misc import imread
im = imread("farm.jpg")
Or, better still if you have Scikit Image installed
或者,如果您安装了 Scikit Image,那就更好了
from skimage.io import imread
im = imread("farm.jpg")
回答by Ashwini Chaudhary
I am not sure if this is the very efficient. But here you go, say arr = np.array(im); then you can do something like this.
我不确定这是否非常有效。但是你去,说arr = np.array(im); 那么你可以做这样的事情。
>>> arr = np.arange(150).reshape(5, 10, 3)
>>> x, y, z = arr.shape
>>> indices = np.vstack(np.unravel_index(np.arange(x*y), (y, x))).T
#or indices = np.hstack((np.repeat(np.arange(y), x)[:,np.newaxis], np.tile(np.arange(x), y)[:,np.newaxis]))
>>> np.hstack((arr.reshape(x*y, z), indices))
array([[ 0, 1, 2, 0, 0],
[ 3, 4, 5, 0, 1],
[ 6, 7, 8, 0, 2],
[ 9, 10, 11, 0, 3],
[ 12, 13, 14, 0, 4],
[ 15, 16, 17, 1, 0],
[ 18, 19, 20, 1, 1],
[ 21, 22, 23, 1, 2],
[ 24, 25, 26, 1, 3],
[ 27, 28, 29, 1, 4],
[ 30, 31, 32, 2, 0],
[ 33, 34, 35, 2, 1],
[ 36, 37, 38, 2, 2],
...
[129, 130, 131, 8, 3],
[132, 133, 134, 8, 4],
[135, 136, 137, 9, 0],
[138, 139, 140, 9, 1],
[141, 142, 143, 9, 2],
[144, 145, 146, 9, 3],
[147, 148, 149, 9, 4]])
回答by u8414853
I used "+" to combine two tuple, and use .append()to make "data" list.No need to use Numpy here.
我用“+”组合了两个元组,.append()用来制作“数据”列表。这里不需要使用Numpy。
row,col = im.size
data=[] #r,g,b,i,j
pixels=im.load()
for i in range(row):
for j in range(col):
data.append(pixels[i,j]+(i,j))

