我是 Python 新手,正在尝试从 numpy 数组中提取 RGB 编码的像素标签。例如:
image.shape
>> (256, 256, 3)
转换为:
image.shape
>> (256, 256, 1)
基于自定义函数。在 Javascript 中,这样的函数将是(当然,确切的 RGB 编码是无关紧要的 - 但能够使用自定义函数是相关的):
RGBtoVal = ([r,g,b])=>{
r = Math.floor(r*9/255);
g = Math.floor(g*9/255);
b = Math.floor(b*9/255);
if (r>0) return r+18;
if (g>0) return r+9;
return b;
}
我知道reshape
和squeeze
有助于降低维度,但没有函数。另外,形状为 (256,256,1) 的 numpy 矩阵与 (256,256) 相同吗?
最佳答案
在 numpy
中,您可以使用向量,而不必单独处理每个像素。
在示例中,我使用图像 4x4
和值 (1,1,1)
import numpy as np
image = np.ones([4,4,3]) # image 4x4 with RGB (3 values)
print(image.shape) # (4, 4, 3)
R = image[:,:,0] # all R values
G = image[:,:,1] # all G values
B = image[:,:,2] # all B values
print(R.shape) # (4, 4)
print(G.shape) # (4, 4)
print(B.shape) # (4, 4)
R = R * 9/255
G = R * 9/255
B = B * 9/255
R[ R > 0 ] += 18
G[ G > 0 ] += 9
print(R)
print(G)
print(B)
print(image)
或者您甚至可以在拆分为 R,G,B
之前使用 * 9/255
import numpy as np
image = np.ones([4,4,3])
print(image.shape)
image = image * 9/255
R = image[:,:,0]
G = image[:,:,1]
B = image[:,:,2]
R[ R > 0 ] += 18
G[ G > 0 ] += 9
print(R)
print(G)
print(B)
print(image)
如果您想以更传统的方式执行此操作,请使用 numpy.apply_along_axis(func, axis, arr)与轴 2
import numpy as np
# --- fuctions ---
def function(rgb):
#rgb = rgb * 9/255
r, g, b = rgb
r = r * 9/255
g = g * 9/255
b = b * 9/255
if r > 0:
r += 18
if g > 0 :
g += 9
return [r,g,b]
# --- main ---
image = np.ones([4,4,3])
print(image.shape)
image = np.apply_along_axis(function, 2, image)
print(image[:,:,0]) # R
print(image[:,:,1]) # G
print(image[:,:,2]) # B
print(image)
关于python - Numpy 展平维度函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62106035/