Skip to content

Instantly share code, notes, and snippets.

@rp4ri
Last active March 12, 2023 06:42
Show Gist options
  • Save rp4ri/41c650ce168c026331abc92d844b9ec4 to your computer and use it in GitHub Desktop.
Save rp4ri/41c650ce168c026331abc92d844b9ec4 to your computer and use it in GitHub Desktop.
Image Processing Useful code snippets

Image Processing useful code snippets

1. Pillow

Installation

pip install Pillow

Open an image

from PIL import Image

image = Image.open("path/to/image.jpg")

Display an image

image.show()

Resize an image

resized_image = image.resize((width, height))

Rotate an image

rotated_image = image.rotate(angle)

Save an image

image.save("path/to/image.jpg")

2. OpenCV

Installation

pip install opencv-python

Read and display an image

import cv2

# Read an image
img = cv2.imread("image.jpg")

# Display the image
cv2.imshow("Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Convert to grayscale

import cv2

# Read an image
img = cv2.imread("image.jpg")

# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Display the grayscale image
cv2.imshow("Gray Image", gray)
cv2.waitKey(0)
cv2.destroyAllWindows()

Resize an image

import cv2

# Read an image
img = cv2.imread("image.jpg")

# Resize the image
resized = cv2.resize(img, (200, 200))

# Display the resized image
cv2.imshow("Resized Image", resized)
cv2.waitKey(0)
cv2.destroyAllWindows()

Treshold an image

import cv2

# Read an image
img = cv2.imread("image.jpg")

# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Threshold the image
_, thresh = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY)

# Display the thresholded image
cv2.imshow("Thresholded Image", thresh)
cv2.waitKey(0)
cv2.destroyAllWindows()

3. Scikit-Image

Installation

pip install scikit-image

Load an image

from skimage import io

image = io.imread("image.jpg")

Display an image

import matplotlib.pyplot as plt

plt.imshow(image)
plt.show()

Resize an image

from skimage import transform

resized_image = transform.resize(image, (200, 200))

Grayscale conversion

from skimage import color

gray_image = color.rgb2gray(image)

Edge detection

from skimage import filters

edges = filters.sobel(gray_image)

Thresholding

from skimage import filters

threshold_value = filters.threshold_otsu(gray_image)
binary_image = gray_image > threshold_value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment