Detecting thresholds in HSV color space (from RGB) using Python / PIL

后端 未结 4 2106
渐次进展
渐次进展 2020-12-01 09:09

I want to take an RGB image and convert it to a black and white RGB image, where a pixel is black if its HSV value is between a certain range and white otherwise.

Cu

4条回答
  •  盖世英雄少女心
    2020-12-01 09:11

    EDIT 2: This now returns the same results as Paul's code, as it should...

    import numpy, scipy
    
    image = scipy.misc.imread("test.png") / 255.0
    
    r, g, b = image[:,:,0], image[:,:,1], image[:,:,2]
    m, M = numpy.min(image[:,:,:3], 2), numpy.max(image[:,:,:3], 2)
    d = M - m
    
    # Chroma and Value
    c = d
    v = M
    
    # Hue
    h = numpy.select([c ==0, r == M, g == M, b == M], [0, ((g - b) / c) % 6, (2 + ((b - r) / c)), (4 + ((r - g) / c))], default=0) * 60
    
    # Saturation
    s = numpy.select([c == 0, c != 0], [0, c/v])
    
    scipy.misc.imsave("h.png", h)
    scipy.misc.imsave("s.png", s)
    scipy.misc.imsave("v.png", v)
    

    which gives hue from 0 to 360, saturation from 0 to 1 and value from 0 to 1. I looked at the results in image format, and they seem good.

    I wasn't sure by reading your question whether it was only the "value" as in V from HSV that you were interested in. If it is, then you can bypass most of this code.

    You can then select pixels based on those values and set them to 1 (or white/black) using something like:

    newimage = (v > 0.3) * 1
    

提交回复
热议问题