Python alternative for loop list generation RGB2HSV

Original double loop writing. More time-consuming

#将RGB色彩空间 转换成HSV色彩空间 
def ConvertRGB2HSV(image):
  w,h,c = image.shape
  newHSVImage = np.zeros((w,h,c), dtype=np.int)
  # print(newHSVImage.shape)

  for wi in range(0,w):
    for hi in range(0,h):
        ch,cs,cv = rgb2hsv(image[wi,hi])
        newHSVImage[wi,hi,0] = ch
        newHSVImage[wi,hi,1] = cs
        newHSVImage[wi,hi,2] = cv
 
  return newHSVImage

The list generation style is very concise, but it is not easy to understand, and it also needs to be reshaped. It is also slower. Opencv comes with which is faster. Opencv is implemented in C language. I should have used other optimization algorithms internally. I I remember that a certain great god rigorously optimized the calculation of tens of seconds to a few milliseconds...It was about color conversion, which was to grayscale at the time. Unfortunately, I couldn't find any article.

#将RGB色彩空间 转换成HSV色彩空间 
def ConvertRGB2HSV(image):
  w,h,c = image.shape 
  newHSVImage = [ rgb2hsv(point) for row in image for point in row] 
  return np.array(newHSVImage).reshape(w,h,c)

Of course, the pursuit of extreme efficiency can be achieved with opencv

    cv2hsvimg = cv2.cvtColor(rgbTensorImage,cv2.COLOR_RGB2HSV)

Subsidy the core rgb to hsv code. Thanks to netizens

###'''
### 根据rgb计算出对应的hsv色彩
###'''
# @jit(nopython=True)
def rgb2hsv(rgb): 
    r, g, b = rgb[0],rgb[1],rgb[2]
    r, g, b = r/255.0, g/255.0, b/255.0
    mx = max(r, g, b)
    mn = min(r, g, b)
    m = mx-mn
    if mx == mn:
        h = 0
    elif mx == r:
        if g >= b:
            h = ((g-b)/m)*60
        else:
            h = ((g-b)/m)*60 + 360
    elif mx == g:
        h = ((b-r)/m)*60 + 120
    elif mx == b:
        h = ((r-g)/m)*60 + 240
    if mx == 0:
        s = 0
    else:
        s = m/mx
    v = mx
    return (h, s, v)

I don’t know why, the hue of the picture I generated turned out to be such an effect. Maybe it’s not right. The
H, S, V effects are as follows,
hue (H) channel,
Insert picture description here
saturation (S) channel,
Insert picture description here
lightness (V) aisle
Insert picture description here

It still feels that our Asian beauties are more beautiful, much better than Lena in the United States. Maybe our Asians have different aesthetics.
Insert picture description here
Uh, uh, let’s put a large Lena here, thank you~ , Http://www.lenna.org/full/l_hires.jpg

How about it? Asian beauties look better... if you agree, please raise your hand.
Insert picture description here

Guess you like

Origin blog.csdn.net/phker/article/details/112509215