hsv识别适用于背景色与目标色单一且反差大的场景,例如这样的:
红色战力和绿色战力,我们的目的是挑战绿色低战力的,用找色很麻烦,因为他们是数字一直是变化的,无法用找色实现,而用hsv就可以轻松实现,具体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