Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
974 views
in Technique[技术] by (71.8m points)

arrays - inverting image in Python with OpenCV

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 single value with this formula (it might be wrong but it seems reasonable for me):

img[x,y] = abs(img[x,y] - 255)

but I don't understand why doesn't it works:

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


def inverte2(imagem, name):
    for x in np.nditer(imagem, op_flags=['readwrite']):
        x = abs(x - 255)
    cv2.imwrite(name, imagem)


if __name__ == '__main__':
    nome = str(sys.argv[1])
    image = cv2.imread(nome)
    gs_imagem = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    inverte(gs_imagem, "invertida.png")
    inverte2(gs_imagem, "invertida2.png")

I don't want to do an explicit loop (I am trying to be more pythonic). I can see that in one image that got a white background it turned black, but only this it doesn't looks like the other colors are having much (if any) change.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...