inverting image in Python with OpenCV

后端 未结 3 431
无人及你
无人及你 2020-12-07 21:44

I want to load a color image, convert it to grayscale, and then invert the data in the file.

What I need: to iterate over the array in OpenCV and change every singl

相关标签:
3条回答
  • 2020-12-07 22:19

    You can use "tilde" operator to do it:

    import cv2
    image = cv2.imread("img.png")
    image = ~image
    cv2.imwrite("img_inv.png",image)
    

    This is because the "tilde" operator (also known as unary operator) works doing a complement dependent on the type of object

    for example for integers, its formula is:

    x + (~x) = -1

    but in this case, opencv use an "uint8 numpy array object" for its images so its range is from 0 to 255

    so if we apply this operator to an "uint8 numpy array object" like this:

    import numpy as np
    x1 = np.array([25,255,10], np.uint8) #for example
    x2 = ~x1
    print (x2)
    

    we will have as a result:

    [230 0 245]
    

    because its formula is:

    x2 = 255 - x1

    and that is exactly what we want to do to solve the problem.

    0 讨论(0)
  • 2020-12-07 22:34

    Alternatively, you could invert the image using the bitwise_not function of OpenCV:

    imagem = cv2.bitwise_not(imagem)
    

    I liked this example.

    0 讨论(0)
  • 2020-12-07 22:44

    You almost did it. You were tricked by the fact that abs(imagem-255) will give a wrong result since your dtype is an unsigned integer. You have to do (255-imagem) in order to keep the integers unsigned:

    def inverte(imagem, name):
        imagem = (255-imagem)
        cv2.imwrite(name, imagem)
    

    You can also invert the image using the bitwise_not function of OpenCV:

    imagem = cv2.bitwise_not(imagem)
    
    0 讨论(0)
提交回复
热议问题