I need to convert an image to HSV. I used the library OpenCV but when I run my algorithm I have the following warning:
RuntimeWarning: overflow encountered in ubyte_scalars
I want to calculate distance between two HSV piexels. I implemented the function:
def distance(pixel1, pixel2):
h1, s1, v1 = pixel1[0], pixel1[1], pixel1[2]
h2, s2, v2 = pixel2[0], pixel2[1], pixel2][2]
dh = abs(h1 - h2) / 179
ds = abs(s1 - s2) / 255
dv = abs(v1 - v2) / 255
distance = math.sqrt(dh ** 2 + ds ** 2 + dv ** 2) / math.sqrt(3)
return distance
When I execute the following code the results are not correct because of the overflow. In some cases the distance is grater than 1.0 and that shouldn't happen.
import cv2
import math
import numpy as np
#threshold value in range (0,1]
threshold = 0.7689
image1 = cv2.imread("image1.jpg")
image2 = cv2.fastNlMeansDenoisingColored(image1,None,10,10,7,21)
image3 = cv2.cvtColor(image2, cv2.COLOR_BGR2HSV)
w, h, c = image3.shape
binary_image = np.zeros((w, h), dtype= int)
# extract one pixel from image
pixel1 = image3[w//2][h//2]
for i in range(w):
for j in range(h):
distance = distance(pixel1, image3[i][j])
if distance > threshold:
binary_image[i][j] = 1
else:
binary_image[i][j] = 0
I tried to do the following change, after I read the image
image4 = np.array(image3, dtype = 'float64')
If I change the type of the array the distance becomes extremely small (< 0.01) and the threshold value can't be applied.
How can I change my code in order to avoid overflow?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…