[英]Efficient color lookup with linear interpolation in Python
我有興趣找到一種快速的方法,用於從定義的查找表中查找線性插值的顏色。 目的是在運行時根據給定的顏色圖將顏色分配給大量項目。 顏色表查找表是一個元組列表,其中包含值(升序),紅色,綠色,藍色,不透明度
以下是使用標准python的簡單食譜。 我也可以使用熊貓,因為我也將其用於其他用途。
# Interpolate colors from a lookup table
import bisect
def find_color(x, vlist, lut):
"""Finds linearly interpolated color from specified lut and x
Returns RGBA tuple
Parameters
x: value to lookup
vlist: list of values in lut
lut: List of tuples Value, R, G, B, A
"""
last = len(lut) - 1 # last index for lut
if x <= vlist[0] : #clamp low end
return lut[0][1], lut[0][2], lut[0][3], lut[0][4]
elif x >= vlist[last]: #clamp high end
return lut[last][1], lut[last][2], lut[last][3], lut[last][4]
else:
# since vlist is sorted we can use bisect
hi = bisect.bisect_left(vlist, x) #hi index
lo = hi - 1 # lo index
# interpolation weight from left
w = ( x - vlist[lo] ) / (vlist[hi] -vlist[lo] )
#print x, lo, hi, w
# use w to interpolate r,g,b,a from lo and hi bins
# interpolated_value = low_value + w * bin_size
r = lut[lo][1] + w * (lut[hi][1] - lut[lo][1])
g = lut[lo][2] + w * (lut[hi][2] - lut[lo][2])
b = lut[lo][3] + w * (lut[hi][3] - lut[lo][3])
a = lut[lo][4] + w * (lut[hi][4] - lut[lo][4])
return int(r), int(g), int(b), int(a)
# Color lookup table
lut = [ (0.0, 255, 0, 0, 64),
(0.5, 0, 255, 255,128),
(1.0, 0, 0, 255, 255) ]
# Value list - extract first column from lut
vlist = [ x[0] for x in lut]
# Test find_color() for arbitrary value
for i in xrange(-5, 12):
x = i/10.0
print find_color(x, vlist, lut)
如果您可以提前對查找表進行預處理,則可以用簡單的查找替換二進制搜索+內插。 只要您願意接受不完全准確的輸出(對於顏色就是這種情況),就很難發現一個錯誤。
將該值乘以某個常數,然后轉換為整數,然后將該整數用作列表的索引。
resolution = 1024
multiplier = float(resolution) / (lut[-1][0] - lut[0][0])
lookup = [(0, 0, 0, 0)] * resolution
for index in range(resolution):
r, g, b, a = find_color(lut[0][0] + i / multiplier, vlist, lut)
lookup[index] = (r, g, b, a)
def find_color2(x):
return lookup[int((x - lut[0][0]) * multiplier)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.