Skip to content

Curiousily

OpenCV Tutorial for Beginners with Python

Computer Vision, OpenCV, Python2 min read

Share

TL;DR Learn how to preprocess images using OpenCV. Read, write, crop, resize, rotate, and many more practical tips included.

  • Run the complete notebook in your browser (Google Colab)
1import cv2
2import matplotlib.pyplot as plt
3import numpy as np
4import seaborn as sns
5from pylab import rcParams
6
7%matplotlib inline
8
9sns.set_style("white")
10
11rcParams['figure.figsize'] = 12, 10
1!gdown --id 16jP0_ESP0PXnrbygsWMeqlIU-jAP6dJ6

Reading an image

There are multiple flags for reading an image

1img = cv2.imread(filename = 'snail.jpg', flags = cv2.IMREAD_COLOR)

Width, height and color channels

1h, w, channels = img.shape
2
3print(f'height: {h}, width: {w}, color channels: {channels}')
1height: 1710, width: 1600, color channels: 3

Show image

This is Toby:

1plt.imshow(cv2.cvtColor(src = img, code = cv2.COLOR_BGR2RGB));

png
png

Toby was an HR representative in a small paper supplier company. His boss was a really cool dude. Sadly, the boss didn’t like Toby, at all!

Default color channels are BGR

On some days, Toby was blue (he didn’t know about weird OpenCV default color channels):

1plt.imshow(img);

png
png

Turning into gray

On some days, he was beyond 50 shades of gray:

1plt.imshow(cv2.cvtColor(src = img, code = cv2.COLOR_BGR2GRAY), cmap = 'gray');

png
png

Saving an image

1cv2.imwrite('snail-gray.jpg', cv2.cvtColor(src = img, code = cv2.COLOR_BGR2GRAY))
1def show_image(image, show_axis=True):
2 plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
3 if not show_axis:
4 plt.axis('off');

Resizing

1resize_width, resize_height = 128, 80
2
3resized = cv2.resize(
4 src = img,
5 dsize=(resize_width, resize_height),
6 interpolation=cv2.INTER_LANCZOS4
7)
8
9show_image(resized)

png
png

Cropping

1cropped = img[400:1200, 50:1550]
2
3show_image(cropped)

png
png

Rotation

On some days, he felt like his head was spinning (coronavirus?):

1# Code by Adrian Rosebrock
2# https://www.pyimagesearch.com/2017/01/02/rotate-images-correctly-with-opencv-and-python/
3
4def rotate_bound(image, angle):
5 # grab the dimensions of the image and then determine the
6 # center
7 (h, w) = image.shape[:2]
8 (cX, cY) = (w // 2, h // 2)
9 # grab the rotation matrix (applying the negative of the
10 # angle to rotate clockwise), then grab the sine and cosine
11 # (i.e., the rotation components of the matrix)
12 M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0)
13 cos = np.abs(M[0, 0])
14 sin = np.abs(M[0, 1])
15 # compute the new bounding dimensions of the image
16 nW = int((h * sin) + (w * cos))
17 nH = int((h * cos) + (w * sin))
18 # adjust the rotation matrix to take into account translation
19 M[0, 2] += (nW / 2) - cX
20 M[1, 2] += (nH / 2) - cY
21 # perform the actual rotation and return the image
22 return cv2.warpAffine(image, M, (nW, nH))
1show_image(rotate_bound(img, 45))

png
png

Blurring an image

Toby was unhappily divorced #exhusband right in the middle of his mid-life crisis.

One day, he decided it was time for a change. He wanted to be successful. He looked around the modern web, in his free time (which is all the time) and noticed something strange.

There were these extremely good looking guys, which others called influencers. They were famous, making lots of cash, and didn’t even have to go to work.

Toby noticed something else. The more good looking the influencer, the more shit he/she can talk without even being questioned (the Law of Toby).

Our hero had a brilliant idea. From now on, he was going to be an influencer. He even shouted it in the office, but nobody really cared.

He quickly created a plan/checklist and started acting (without a second thought). He was learning OpenCV, on the side. Finally, those skills were going to pay off.

He needed a gym:

1!gdown --id 1vpUJWPcjhJ6qY9ebZ3uQGlP0OYSocXJg
1background = cv2.imread('gym.jpg', cv2.IMREAD_COLOR)
2h, w, _ = background.shape
3
4background = cv2.resize(background, (w // 2, h // 2))
5
6show_image(background)

png
png

But he was the star of the show, so the gym shouldn’t be so edgy:

1kernel_len = 21
2blurred_background = cv2.GaussianBlur(
3 src = background,
4 ksize = (kernel_len, kernel_len),
5 sigmaX = 120,
6 sigmaY = 45
7)
8
9show_image(blurred_background)

png
png

Finding contours of an image

Naturally, he should be front and center of the show:

1gray = cv2.cvtColor(cropped, cv2.COLOR_BGR2GRAY)
2_, binary = cv2.threshold(
3 src = gray,
4 thresh = 225,
5 maxval = 255,
6 type = cv2.THRESH_BINARY_INV
7)
8
9contours, _ = cv2.findContours(
10 image = binary,
11 mode = cv2.RETR_EXTERNAL,
12 method = cv2.CHAIN_APPROX_SIMPLE
13)
14
15contour_img = cropped.copy()
16
17show_image(
18 cv2.drawContours(
19 image = contour_img,
20 contours = contours,
21 contourIdx = -1,
22 color = (0, 255, 0),
23 thickness = 20
24 )
25)

png
png

Placing one image on top of another

Toby was determined to present himself in the best way possible. So he would cut himself out from the best portrait picture he had (using a mask):

1mask = np.zeros_like(cropped)
2mask = cv2.drawContours(mask, contours, -1, (255, 255, 255), cv2.FILLED)
3
4show_image(mask)

png
png

1masked_snail = cv2.bitwise_and(
2 src1 = cropped,
3 src2 = cropped,
4 mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
5)
1show_image(masked_snail)

png
png

And place himself at the magical gym selfie spot:

1new_mask = np.zeros_like(blurred_background)
2new_mask[
3 650: 650 + masked_snail.shape[0],
4 750: 750 + masked_snail.shape[1]
5] = masked_snail
6
7show_image(new_mask)

png
png

Finally, he could place himself on top of the gym background:

1_, alpha = cv2.threshold(
2 src = cv2.cvtColor(new_mask, cv2.COLOR_RGB2GRAY),
3 thresh = 0,
4 maxval = 255,
5 type = cv2.THRESH_BINARY
6)
7
8b, g, r = cv2.split(new_mask)
9alpha_image = cv2.merge((b, g, r, alpha))
10
11final_image = blurred_background.copy()
12
13alpha_s = alpha_image[:, :, 3] / 255.0
14alpha_l = 1.0 - alpha_s
15
16for c in range(0, 3):
17final_image[:, :, c] = (alpha_s _ alpha_image[:, :, c] +\
18 alpha_l _ final_image[:, :, c])
19
20show_image(final_image)

png
png

Drawing circles

He also heard that blue eyes sell well:

1image = final_image.copy()
2
3eye_coordinates = [(1985, 690), (2025, 800)]
4
5for ec in eye_coordinates:
6 image = cv2.circle(
7 img = image,
8 center = ec,
9 radius = 30,
10 color = (255, 0, 0),
11 thickness = -1
12 )
13
14show_image(image)

png
png

Drawing text

Finally, he had to make it a bit “по-така” (yes, knowing bulgarian is the SuperPower to have). He needed a special hashtag:

1final_img = image.copy()
2
3cv2.putText(
4 img = final_img,
5 text = '#gymsnail',
6 org = (150, final_img.shape[0] - 100),
7 fontFace = cv2.FONT_HERSHEY_SIMPLEX,
8 fontScale = 8,
9 color = (0, 255, 0),
10 thickness = 23
11)
12
13show_image(final_img)

png
png

The plan was executed flawlessly. It took him only 3 years. He was starting his own fitness brand. It was going to be an epic experience. He was already imagining all the glute-focused workouts he was going to witness. That was the life he was always dreamed of!

He now had to do only one thing. Remember his super-secret password for all his social media accounts. Uncle Pesho had shown him TikTok, but sadly, he’s been logged out for a long time.

He uploaded his new image and started waiting. Still waiting for that day!

Share

Want to be a Machine Learning expert?

Join the weekly newsletter on Data Science, Deep Learning and Machine Learning in your inbox, curated by me! Chosen by 10,000+ Machine Learning practitioners. (There might be some exclusive content, too!)

You'll never get spam from me