Python, OpenCV: Increasing image brightness without overflowing UINT8 array

前端 未结 5 2171
花落未央
花落未央 2020-12-03 18:42

I am trying to increase brightness of a grayscale image. cv2.imread() returns a numpy array. I am adding integer value to every element of the array. Theoretica

5条回答
  •  被撕碎了的回忆
    2020-12-03 19:37

    I ran into a similar issue, but instead of addition, it was scaling image pixels in non-uniform manner.

    The 1-D version of this:

    a=np.array([100,200,250,252,255],dtype=np.uint8)
    scaling=array([ 1.1,  1.2,  1.4,  1.2,  1.1])
    result=np.uint8(a*scaling)
    

    This gets you the overflow issue, of course; the result:

    array([110, 240,  94,  46,  24], dtype=uint8)
    

    The np.where works:

    result_lim=np.where(a*scaling<=255,a*scaling,255)
    

    yields result_lim as:

    array([ 110.,  240.,  255.,  255.,  255.])
    

    I was wondering about timing, I did this test on a 4000 x 6000 image (instead of 1D array), and found the np.where(), at least for my conditions, took about 2.5x times as long. Didn't know if there was a better/faster way of doing this. The option of converting to float, doing the operation, and then clipping as noted above was a bit slower than the np.where() method.

    Don't know if there are better methods for this.

提交回复
热议问题