Image Processing in OpenCV Python

[This article was first published on Python – Predictive Hacks, and kindly contributed to python-bloggers]. (You can report issue about the content on this page here)
Want to share your content on python-bloggers? click here.

We will show how you can apply image processing with OpenCV in Python. We will work with this image obtained from Unsplash.

Image Processing in OpenCV Python 1

How to blur the Image

import cv2
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

img = cv2.imread('panda.jpeg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
blurred_img = cv2.blur(img,ksize=(20,20))
cv2.imwrite("blurredpanda.jpg", blurred_img) 
 
Image Processing in OpenCV Python 2

How to apply Sobel Operator

You can have a look about Sobel Operator at Wikipedia and you can also start experimenting with some filters. Let’s apply the horizontal and vertical Sobel Operator.

img = cv2.imread('panda.jpeg',0)
sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=5)
sobely = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=5)

cv2.imwrite("sobelx_panda.jpg", sobelx) 
cv2.imwrite("sobely_panda.jpg", sobely) 
 
 
Image Processing in OpenCV Python 3
Image Processing in OpenCV Python 4

How to apply a threshold to an Image

We can also binarize the images.

img = cv2.imread('panda.jpeg',0)
ret,th1 = cv2.threshold(img,100,255,cv2.THRESH_BINARY)
fig = plt.figure(figsize=(12,10))
plt.imshow(th1,cmap='gray')
Image Processing in OpenCV Python 5
To leave a comment for the author, please follow the link and comment on their blog: Python – Predictive Hacks.

Want to share your content on python-bloggers? click here.