0

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?

AlexDr
  • 13
  • 4
  • 1
    the overflow is because you are taking 0-255 uint8 integer and **2. converting it to np.float is the right approach. The <0.01 does not make sense. Take 2 example pixels and calculate their dist manually and then follow the program steps. – Lior Cohen Dec 21 '20 at 20:14
  • @LiorCohen if the pixels are neighbours the distance is smaller than 0.1. For example if I have the values pixel1 = [ 92. 137. 97.] and pixel2 = [ 91. 135. 98.] the distance would be 0.0060028747188588345 – AlexDr Dec 21 '20 at 20:44
  • @Alex, for that example pixel1 = [ 92. 137. 97.] and pixel2 = [ 91. 135. 98.], what distance do you expect, and what distance does the code compute? I notice in `distance()` that the dh, ds, dv differences are divided by 179 and 255, and the final distance is divided by sqrt(3), so I'd expect colors that differ by a couple levels like your example would have distance of the order of 2/(179*sqrt(3)) = 0.006. – Pascal Getreuer Dec 22 '20 at 00:10

0 Answers0