# lua触动精灵rgb转hsv函数方法

hsv识别适用于背景色与目标色单一且反差大的场景，例如这样的：

--rgb转hsv，返回h,s,v三个值
function rgb2hsv(r,g,b)
-- 找出r,g,b最小值和最大值
local min = math.min(r,g,b)
local max = math.max(r,g,b)
local diff = max - min
local h,s,v = 0,0,0
v = max

if max == 0 then
s = 0
else
s = diff
end

if diff ~= 0 then

if r == max then
h = 60 * (g - b) / diff
elseif g == max then
h = 60 * (b - r) / diff + 120
else
h = 60 * (r - g) / diff + 240
end

if h < 0 then
h = h + 360
end
else
h = -1
end

local tmp = math.modf(h)
return tmp,s,v
end

-- 通过色相来模糊查找区域指定颜色，返回坐标,offset为偏移值，一般设置为5就可以
-- 此函数适用于颜色反差较大区域
function findHsvInRegionFuzzy(color, offset, x0, y0, x1, y1)
local width = math.abs(x1-x0) or 0
local height = math.abs(y1-y0) or 0

if(width==0) or (height==0) or (offset<0) then
return -1, -1
end

local num = string.format("%06x",color)
local r = tonumber(string.sub(num,1,2),16)
local g = tonumber(string.sub(num,3,4),16)
local b = tonumber(string.sub(num,5,6),16)
local h= rgb2hsv(r,g,b)
local x,y =-1,-1
local rx,ry=-1,-1

-- 缓存图片，效率提高50倍 :)
keepScreen(true)
for i= 0, height do
y = y0 + i
for j =0, width do
x = x0 + j
local r1,g1,b1 = getColorRGB(x,y)
local h1 = rgb2hsv(r1,g1,b1)
if math.abs(h1-h) < offset then
rx = x
ry = y
goto endfor
end
end
end
::endfor::
keepScreen(false)

return rx,ry
end

11-30 1191
02-22 1122
04-19 1万+
05-20 5万+
08-21 5367
01-22 2190
12-03 407
10-07 771
07-03 1050
08-02 2822
05-04 4339
03-31 593
02-29 3525
05-14 8344
10-08