[英]Convert RGB pixel values in a range to consecutive numbers
伙计们,我是python的新手,但我对此深信不疑。 如果您能帮助我,将不胜感激。
我有一个图像,每个像素中都有许多颜色。 它们都表示一个数字。
使用从0到15625像素的此范围构建图像。 从0到15625范围内的每个像素都有不同的颜色,并且使用该颜色构造了上面的图像。
图片范围 (非常大,因此您可能需要下载它才能查看图片)
我想做的是将RGB值从第一个像素值(5,5,5)转换为1,将下一个像素值转换为2,依此类推。 因此,上图中的每个像素可能对应一个值。
这类似于这个问题,但是我不认为它可以完成我想做的事情。 如何将图像的所有像素值转换为特定范围-python
这是我用来创建范围的代码
#!/usr/local/bin/python3
from PIL import Image
import numpy as np
# Create array to hold output image
result=np.zeros([1,25*25*25,3],dtype=np.uint8)
#change the values above i.e. 51*51*51 done by (upperbound-lowerbound)/step i.e (255-0)/5
j=0
for r in range(5,255,10):
for g in range(5,255,10):
for b in range(5,255,10):
result[0,j]= (r,g,b)
j+=1
# Convert output array to image and save
im=Image.fromarray(result)
im.save("perfect1.png")
这是查找范围内每个像素的RGB值的代码
from PIL import Image
i = Image.open('perfect1.png')
pixels = i.load() # this is not a list, nor is it list()'able
width, height = i.size
all_pixels = []
for x in range(width):
for y in range(height):
cpixel = pixels[x, y]
all_pixels.append(cpixel)
print all_pixels
这是用于创建没有额外像素值的子数组的代码,因为图像中的每个“像素”值都包含许多像素。 a =图像值数组
rows_mask = np.insert(np.diff(a[:, 0]).astype(np.bool), 0, True)
columns_mask = np.insert(np.diff(a[0]).astype(np.bool), 0, True)
b = a[np.ix_(rows_mask, columns_mask)]
这是一些主意。
让我们加载您的图像
import numpy as np
from scipy.misc import imread
img = imread("img.png")[..., :3] # drop alpha channel
lut = imread("lut.png").squeeze() # squeeze 1D first axis
print(img.shape)
print(lut.shape)
哪个输出
(589, 612, 3)
(15625, 3)
现在假设我们要查找图像中的第一个像素
print(img[0, 0])
[245 245 95]
您可以在查找表中找到所有具有相同值的像素( axis=1
以逐行比较)
np.all(img[0, 0] == lut, axis=1)
这为您提供了所有像素的遮罩,对于匹配项为True
,否则为False
。
现在,您可以使用np.where
将其转换为索引列表(在您的情况下,我们假设其长度为1
)。
idx = np.where(np.all(img[0, 0] == lut, axis=1))
并且,假设每个像素都有一个唯一的映射,您将获得
(array([15609]),)
现在,此方法确实非常缓慢且效率低下,您必须对图像的每个像素重复此方法。 可能有某种方法可以加快它的速度,但是目前我还没有看到它,让我们看看是否还有其他人有更好的输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.