San*_*ket 11 python numpy python-imaging-library
我想将图像转换为具有5列的2D数组,其中每行都是表格[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
Run Code Online (Sandbox Code Playgroud)
YXD*_*YXD 14
最近我不得不写这篇文章并最终结束
indices = np.dstack(np.indices(im.shape[:2]))
data = np.concatenate((im, indices), axis=-1)
Run Code Online (Sandbox Code Playgroud)
imnumpy数组在哪里?您可能最好直接将图像读入numpy数组
from scipy.misc import imread
im = imread("farm.jpg")
Run Code Online (Sandbox Code Playgroud)
或者,如果您安装了Scikit Image,则更好
from skimage.io import imread
im = imread("farm.jpg")
Run Code Online (Sandbox Code Playgroud)
我不确定这是否非常有效.但是,你走了,说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]])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
47639 次 |
| 最近记录: |