我正在尝试比较 HSV 颜色空间中的两个像素并计算它们的绝对差。我的代码似乎对 S & V 频道正确执行。然而,H 通道大多数时候都会给出正确的值,但有时它会给我一个完全不合理的结果。
我在代码中做什么:
我似乎对 HSV 色彩空间有一些误解。 经过对 stackoverflow 的一些研究,我针对 H 通道的 360 限制比较和 V 通道的 255 比较实现了 min 函数。然而,时不时地我仍然得到 H 通道的错误结果。
import cv2 as cv
import numpy as np
import pyautogui
import time
tilling_target = cv.imread("tilling_target7.png")
tilling_target = np.array(tilling_target)
cap = cv.VideoCapture("video.mp4")
'Move to starting Lure Position'
ret, frame = cap.read()
lure_location = cv.matchTemplate(
frame,
tilling_target,
cv.TM_CCOEFF_NORMED)
loc_arr = np.array(location)
min_val, max_val, min_loc, max_loc = cv.minMaxLoc(loc_arr)
print(max_loc)
frameHSV = cv.cvtColor(frame, cv.COLOR_BGR2HSV)
urpixel = frameHSV[max_loc[1]+20, max_loc[0]-40]
start_time = time.time()
'Watch the lure and changes'
while True:
ret, frame = cap.read()
frameHSV = cv.cvtColor(frame, cv.COLOR_BGR2HSV)
pixel = frameHSV[max_loc[1]+20, max_loc[0]-40]
print("urpixel:",urpixel)
print("pixel:",pixel)
print("time:",time.time()-start_time)
dif_to_urpixel = [min(abs(pixel[0]-urpixel[0]), 360-abs((pixel[0]-urpixel[0]))), abs(pixel[1]-urpixel[1]), min(abs(pixel[2]-urpixel[2]), 255-abs(pixel[2]-urpixel[2]))]]
print("differenz:",dif_to_urpixel)
print("sum diff:", sum(dif_to_urpixel))
urpixel: [100 114 65]
pixel: [101 138 63]
time: 3.048245668411255
differenz: [1, 24, 1] **--> working as intended**
sum diff: 26
urpixel: [100 114 65]
pixel: [ 99 124 74]
time: 3.2529683113098145
differenz: [105, 10, 9] **--> 100-99 should result in 1 and not 105??**
sum diff: 124
urpixel: [100 114 65]
pixel: [101 143 57]
time: 6.2827301025390625
differenz: [1, 29, 7] **--> working as intended**
urpixel: [100 114 65]
pixel: [ 99 134 57]
time: 5.828529596328735
differenz: [105, 20, 7] **--> Again resulting in 105 instead of 1**
正如 Mark 所提到的,OpenCV 将 H 坐标缩放到 0->179 的范围并使用 uint8。 因此,
abs(negative_value)
不是一个好的做法,除非您将值转换为 int 或 float 并且您还应该使用 180-abs(diff)
而不是 360-abs(diff)