— Computer Vision, OpenCV, Python — 2 min read
Share
TL;DR Learn how to preprocess images using OpenCV. Read, write, crop, resize, rotate, and many more practical tips included.
1import cv22import matplotlib.pyplot as plt3import numpy as np4import seaborn as sns5from pylab import rcParams67%matplotlib inline89sns.set_style("white")1011rcParams['figure.figsize'] = 12, 10
1!gdown --id 16jP0_ESP0PXnrbygsWMeqlIU-jAP6dJ6
There are multiple flags for reading an image
1img = cv2.imread(filename = 'snail.jpg', flags = cv2.IMREAD_COLOR)
1h, w, channels = img.shape23print(f'height: {h}, width: {w}, color channels: {channels}')
1height: 1710, width: 1600, color channels: 3
This is Toby:
1plt.imshow(cv2.cvtColor(src = img, code = cv2.COLOR_BGR2RGB));
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!
On some days, Toby was blue (he didn’t know about weird OpenCV default color channels):
1plt.imshow(img);
On some days, he was beyond 50 shades of gray:
1plt.imshow(cv2.cvtColor(src = img, code = cv2.COLOR_BGR2GRAY), cmap = 'gray');
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');
1resize_width, resize_height = 128, 8023resized = cv2.resize(4 src = img,5 dsize=(resize_width, resize_height),6 interpolation=cv2.INTER_LANCZOS47)89show_image(resized)
1cropped = img[400:1200, 50:1550]23show_image(cropped)
On some days, he felt like his head was spinning (coronavirus?):
1# Code by Adrian Rosebrock2# https://www.pyimagesearch.com/2017/01/02/rotate-images-correctly-with-opencv-and-python/34def rotate_bound(image, angle):5 # grab the dimensions of the image and then determine the6 # center7 (h, w) = image.shape[:2]8 (cX, cY) = (w // 2, h // 2)9 # grab the rotation matrix (applying the negative of the10 # angle to rotate clockwise), then grab the sine and cosine11 # (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 image16 nW = int((h * sin) + (w * cos))17 nH = int((h * cos) + (w * sin))18 # adjust the rotation matrix to take into account translation19 M[0, 2] += (nW / 2) - cX20 M[1, 2] += (nH / 2) - cY21 # perform the actual rotation and return the image22 return cv2.warpAffine(image, M, (nW, nH))
1show_image(rotate_bound(img, 45))
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.shape34background = cv2.resize(background, (w // 2, h // 2))56show_image(background)
But he was the star of the show, so the gym shouldn’t be so edgy:
1kernel_len = 212blurred_background = cv2.GaussianBlur(3 src = background,4 ksize = (kernel_len, kernel_len),5 sigmaX = 120,6 sigmaY = 457)89show_image(blurred_background)
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_INV7)89contours, _ = cv2.findContours(10 image = binary,11 mode = cv2.RETR_EXTERNAL,12 method = cv2.CHAIN_APPROX_SIMPLE13)1415contour_img = cropped.copy()1617show_image(18 cv2.drawContours(19 image = contour_img,20 contours = contours,21 contourIdx = -1,22 color = (0, 255, 0),23 thickness = 2024 )25)
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)34show_image(mask)
1masked_snail = cv2.bitwise_and(2 src1 = cropped,3 src2 = cropped,4 mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)5)
1show_image(masked_snail)
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_snail67show_image(new_mask)
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_BINARY6)78b, g, r = cv2.split(new_mask)9alpha_image = cv2.merge((b, g, r, alpha))1011final_image = blurred_background.copy()1213alpha_s = alpha_image[:, :, 3] / 255.014alpha_l = 1.0 - alpha_s1516for c in range(0, 3):17final_image[:, :, c] = (alpha_s _ alpha_image[:, :, c] +\18 alpha_l _ final_image[:, :, c])1920show_image(final_image)
He also heard that blue eyes sell well:
1image = final_image.copy()23eye_coordinates = [(1985, 690), (2025, 800)]45for ec in eye_coordinates:6 image = cv2.circle(7 img = image,8 center = ec,9 radius = 30,10 color = (255, 0, 0),11 thickness = -112 )1314show_image(image)
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()23cv2.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 = 2311)1213show_image(final_img)
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
You'll never get spam from me