Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 549
Mansueli Avatar asked Oct 25 '13 02:10

Mansueli


People also ask

How do you invert frames in OpenCV?

OpenCV-Python is a library of programming functions mainly aimed at real-time computer vision. cv2. flip() method is used to flip a 2D array. The function cv::flip flips a 2D array around vertical, horizontal, or both axes.

How do you flip the camera on an OpenCV?

In cv2. flip() argument try using 0 if you want to flip in y axis, 1 if you want to flip in x axis and -1 if want to flip in both axes.

How do you invert a binary image?

If you have a binary image binImage with just zeroes and ones, there are a number of simple ways to invert it: binImage = ~binImage; binImage = 1-binImage; binImage = (binImage == 0); Then just save the inverted image using the function IMWRITE.


2 Answers

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) 
like image 55
Saullo G. P. Castro Avatar answered Sep 19 '22 23:09

Saullo G. P. Castro


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

imagem = cv2.bitwise_not(imagem) 

I liked this example.

like image 42
Eric Olmon Avatar answered Sep 22 '22 23:09

Eric Olmon