使用 OpenCV 在 Python 中反转图像 [英] inverting image in Python with OpenCV

查看:116
本文介绍了使用 OpenCV 在 Python 中反转图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我不想做一个显式循环(我试图变得更加 Pythonic).我可以看到,在一张白色背景的图像中,它变成了黑色,但仅此而已,其他颜色看起来并没有太大(如果有)变化.

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)

您也可以使用 OpenCV 的 bitwise_not 函数反转图像:

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

imagem = cv2.bitwise_not(imagem)

这篇关于使用 OpenCV 在 Python 中反转图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆