Life2Coding
Create Negative or Invert Image using OpenCV Python

This post will be helpful in learning OpenCV using Python programming. Here I will show how to implement OpenCV functions and apply them in various aspects using some great examples. Then the output will be visualized along with the comparisons.

We will also discuss the basic of image processing and provide the detail explanation related to the OpenCV functions.

Requirements:

First, you need to setup your Python Environment with OpenCV. You can easily do it by following Life2Coding’s tutorial on YouTube: Linking OpenCV with Python 3

Goals:

The goal is to make you understand how to invert color images using opencv python library

Documentation:

imread()

retval=cv.imread(filename[, flags])

Loads an image from a file.

Parameters
filename Name of file to be loaded.
flags Flag that can take values of cv::ImreadModes

imshow()

None=cv.imshow(winname, mat)

Displays an image in the specified window.

Parameters
winname Name of the window.
mat Image to be shown.

bitwise_not()

dst=cv.bitwise_not(src[, dst[, mask]])

Inverts every bit of an array.

Parameters
src input array.
dst output array that has the same size and type as the input array.
mask optional operation mask, 8-bit single channel array, that specifies elements of the output array to be changed.

waitKey()

retval=cv.waitKey([, delay])

Waits for a pressed key.

Parameters
delay Delay in milliseconds. 0 is the special value that means “forever”.

destroyAllWindows()

None=cv.destroyAllWindows()

Destroys all of the HighGUI windows.

Steps:

  • Open the image using cv2.imread()
  • Do NOT Operation using cv2.bitwise_not()
  • Display all the images using cv2.imshow()
  • Wait for keyboard button press using cv2.waitKey()
  • Exit window and destroy all windows using cv2.destroyAllWindows()

Example Code:

import cv2

img = cv2.imread("./hanif.jpg")
cv2.imshow("Pic",img)

img_not = cv2.bitwise_not(img)
cv2.imshow("Invert1",img_not)
cv2.waitKey(0)
cv2.destroyAllWindows()


Output:

5cc104a8905b1 Create Negative or Invert Image using OpenCV Python
life2coding_icon [] Create Negative or Invert Image using OpenCV Python

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.