本文介绍了在python中将图像转换为2D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将图像转换为具有5列的2D数组,其中每行的格式为[r, g, b, x, y]
. x,y是像素的位置,r,g,b是像素值. (我将使用此数组作为机器学习模型的输入).在python中有比这更有效的实现吗?
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?
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
推荐答案
我最近不得不写这篇文章并以
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)
im
是一个numpy数组.您可能最好用
Where im
is a numpy array. You are probably better off reading the images straight into numpy arrays with
from scipy.misc import imread
im = imread("farm.jpg")
或者,如果您已安装Scikit映像,则更好
Or, better still if you have Scikit Image installed
from skimage.io import imread
im = imread("farm.jpg")
这篇关于在python中将图像转换为2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!