用 OpenCV 实现 Python 中的图像反演

我想加载一个彩色图像,将其转换为灰度,然后反转文件中的数据。

我需要做的: 在 OpenCV 中迭代数组,并用这个公式更改每个值(它可能是错误的,但对我来说似乎是合理的) :

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

但我不明白为什么它不起作用:

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")

我不想做一个明确的循环(我试图更加 Python 化)。我可以看到,在一个图像,得到一个白色的背景,它变成黑色,但只有这一点,它看起来不像其他颜色有很大的变化(如果有)。

267189 次浏览

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)

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

imagem = cv2.bitwise_not(imagem)

I liked this example.

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.

You can also do it with numpy.

import cv2
import numpy as np


image = cv2.imread('your_image', 0)
inverted = np.invert(image)


cv2.imwrite('inverted.jpg', inverted)

Why not use the first line in the question with numpy?

inverted = np.abs(image - 255)

Just as simple as that. No iteration or any other function needed. numpy does that automatically for us :)

In Python/OpenCV, I think you want:

img = cv2.absDiff(img, 255)