反转图像在Python与OpenCV的 [英] 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.
我需要:遍历在OpenCV的阵列上,并与这个公式改变每一个值(它可能是错误的,但对我来说似乎是合理的):
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")
我不想做一个明确的循环(我想是更Python)。我可以看到,在得到了一个白色背景原来黑色的形象,但仅此并不看起来像其他的颜色有很多(如果有的话)的变化。
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.
推荐答案
您几乎做到了。你被事实欺骗了 ABS(IMAGEM-255)
会给,因为你的 DTYPE
是一个无符号的一个错误的结果整数。你要做的(255 IMAGEM)
以保持整数符号:
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)
这篇关于反转图像在Python与OpenCV的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!