猿问

将带有图像数据的 numpy 数组转换为长格式

我想将图像转换为“长格式”并返回。我现在的代码是


import numpy as np

import pandas as pd


img = mpimg.imread('/path/image.png')


image = []

for i in range(img.shape[0]):

    for j in range(img.shape[1]):

        image.append([i, j] + img[i, j].tolist())

image = np.array(image)

但我确信有一个更高效的,但奇怪的是在互联网上找不到任何东西。什么是更快的解决方案?


上面的代码产生了正确的结果。我的图像是彩色的,img.shape三元组也是如此。


月关宝盒
浏览 130回答 3
3回答

一只名叫tom的猫

这是一种方法 -m,n = img.shape[:2]r,c = np.mgrid[:m,:n]out = np.column_stack((r.ravel(), c.ravel(), img.reshape(-1,img.shape[2])))替代获得r,c:r,c = np.indices(img.shape[:2])另一个带有数组分配的 -m,n,r = img.shapeout = np.empty((m,n,2+r), dtype=img.dtype)out[:,:,0] = np.arange(m)[:,None]out[:,:,1] = np.arange(n)out[:,:,2:] = imgout = out.reshape(m*n,-1)

拉莫斯之舞

这是一种使用np.indices,转置以匹配您的循环并重新整形以获得二维数组的方法。ix = np.transpose(np.indices(img.shape[:2]), (1,2,0))image = np.concatenate((ix, img), axis=2).reshape(-1, image.shape[2] + 2)

三国纷争

只是为了获得时间:import matplotlib.image as mpimgimport numpy as npimport pandas as pdimport timet0 = time.time()image_orig = []for i in range(img.shape[0]):    for j in range(img.shape[1]):        image_orig.append([i, j] + img[i, j].tolist())image_orig = np.array(image_orig)print(time.time() - t0)t0 = time.time()ix = np.transpose(np.indices(img.shape[:2]), (1,2,0))image = np.concatenate((ix, img), axis=2).reshape(-1, img.shape[2] + 2)print(time.time() - t0)t0 = time.time()m,n = img.shape[:2]r,c = np.indices(img.shape[:2])out = np.column_stack((r.ravel(), c.ravel(), img.reshape(-1,img.shape[2])))print(time.time() - t0)t0 = time.time()m,n,r = img.shapeout = np.empty((m,n,2+r), dtype=img.dtype)out[:,:,0] = np.arange(m)[:,None]out[:,:,1] = np.arange(n)out[:,:,2:] = imgout = out.reshape(m*n,-1)print(time.time() - t0)0.172110080718994140.0014343261718750.00135231018066406250.0008423328399658203最后一个变体似乎是最快的。
随时随地看视频慕课网APP

相关分类

Python
我要回答