[英]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.