Unlock Python OpenCV: Load, Resize, Threshold, and Transform Images

This tutorial demonstrates how to use Python's OpenCV library to read and display images, perform resizing, convert to HSV, apply binary thresholding, execute erosion and dilation, and replace specific pixel colors, providing step-by-step code examples and visual results for each operation.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Unlock Python OpenCV: Load, Resize, Threshold, and Transform Images

1. Image Source

This image is sourced from Baidu Images; it is used solely for knowledge sharing.

2. Read and Display Image

imread(): read image

imshow(): display image

waitKey(): keep window open

import cv2
import numpy as np
# Read image
img = cv2.imread('girl.jpg')
# Show image
cv2.imshow('img', img)
# Wait indefinitely
cv2.waitKey(0)

Result:

3. Image Resizing

resize(): scale image; fx and fy are scaling factors (0.5 halves size)

import cv2
import numpy as np
img = cv2.imread('girl.jpg')
img = cv2.resize(img, None, fx=0.5, fy=0.5)
rows, cols, channels = img.shape
print(rows, cols, channels)
cv2.imshow('img', img)
cv2.waitKey(0)

Result:

4. Convert Image to HSV

Convert a color image to HSV to enable morphological operations.

import cv2
import numpy as np
img = cv2.imread('girl.jpg')
img = cv2.resize(img, None, fx=0.5, fy=0.5)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
cv2.imshow('hsv', hsv)
cv2.waitKey(0)

Result:

5. Binarize Image

Define lower and upper HSV bounds and apply inRange to obtain a binary mask.

import cv2
import numpy as np
img = cv2.imread('girl.jpg')
img = cv2.resize(img, None, fx=0.5, fy=0.5)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
lower_blue = np.array([90, 70, 70])
upper_blue = np.array([110, 255, 255])
mask = cv2.inRange(hsv, lower_blue, upper_blue)
cv2.imshow('mask', mask)
cv2.waitKey(0)

Result:

6. Erosion and Dilation

Apply erosion and dilation to reduce noise in the binary image.

import cv2
import numpy as np
img = cv2.imread('girl.jpg')
img = cv2.resize(img, None, fx=0.5, fy=0.5)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
lower_blue = np.array([90, 70, 70])
upper_blue = np.array([110, 255, 255])
mask = cv2.inRange(hsv, lower_blue, upper_blue)
erode = cv2.erode(mask, None, iterations=1)
dilate = cv2.dilate(erode, None, iterations=1)
cv2.imshow('erode', erode)
cv2.imshow('dilate', dilate)
cv2.waitKey(0)

Result:

7. Replace Pixels by Color

Iterate over each pixel of the eroded mask; replace white pixels with red in the original image.

import cv2
import numpy as np
img = cv2.imread('girl.jpg')
img = cv2.resize(img, None, fx=0.5, fy=0.5)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
lower_blue = np.array([90, 70, 70])
upper_blue = np.array([110, 255, 255])
mask = cv2.inRange(hsv, lower_blue, upper_blue)
erode = cv2.erode(mask, None, iterations=1)
rows, cols, _ = img.shape
for i in range(rows):
    for j in range(cols):
        if erode[i, j] == 255:
            img[i, j] = (0, 0, 255)  # BGR red
cv2.imshow('result', img)
cv2.waitKey(0)

Result:

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonImage ProcessingOpenCVmorphologyPixel Manipulation
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.