[go: up one dir, main page]

0% found this document useful (0 votes)
13 views5 pages

Dip Lab

The document provides an overview of the Python Imaging Library (PIL), detailing methods for opening, displaying, and manipulating images, including resizing, cropping, and rotating. It also covers image creation using NumPy, different image modes, and techniques for image sampling and quantization. Additionally, it explains image connectivity concepts (N4 and N8) and includes example code for various image operations.

Uploaded by

Manav Mavani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views5 pages

Dip Lab

The document provides an overview of the Python Imaging Library (PIL), detailing methods for opening, displaying, and manipulating images, including resizing, cropping, and rotating. It also covers image creation using NumPy, different image modes, and techniques for image sampling and quantization. Additionally, it explains image connectivity concepts (N4 and N8) and includes example code for various image operations.

Uploaded by

Manav Mavani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Python Imaging Library (PIL)

 .open("name"): Opens an image.

 .show(): Displays the image.

 .format: Image format (e.g., jpg, jpeg).

 .mode: Image mode (e.g., RGB, grayscale).

 .size: Size of the image.

 .pale e: Refers to a set of colors used by the image. In formats like GIF or PNG, each pixel is
represented by an index poin ng to a color in the pale e.

Image Opera ons

 .resize(()): Resizes the image. This does not maintain the aspect ra o automa cally unless
explicitly handled. Use when you need a specific size.

 .copy(): Creates a copy of the image.

 .thumbnail(()): Resizes the image to fit within a defined size while maintaining the aspect
ra o.

 .rotate(angle=, expand=): Rotates the image counter-clockwise. If expand=True, the image is


expanded to avoid clipping.

 .crop((x,y,z,w)): Crops the image to the defined rectangle (from le , top, right, bo om).

Crea ng Custom Images

import numpy as np

from PIL import Image

# Create custom images (white, grey, black)

img_white = 255 * np.ones((100, 300), dtype=np.uint8)

img_grey = 200 * np.ones((100, 300), dtype=np.uint8)

img_black = np.zeros((100, 300), dtype=np.uint8)

img_final = np.concatenate((img_black, img_grey, img_white))

# Convert the final image array to an image object

final = Image.fromarray(img_final)

# Flip an image ver cally

flipped_tb = im1_org.transpose(Image.FLIP_TOP_BOTTOM) # Flip ver cally


Image Modes

 1: 1-bit pixel (black and white).

 L: 8-bit pixel (grayscale values between 0 to 255).

 P: 8-bit color pale e (used in formats like GIF).

 RGB: Red, Green, Blue (each value 8-bit).

Spli ng RGB into Channels

To split RGB channels into separate individual channels:

r, g, b = img.split() # Separate Red, Green, and Blue channels

Image Sampling

Image sampling refers to represen ng a con nuous image as a discrete set of pixel values. This can
involve downsampling (reducing resolu on) through resizing.

Resizing Methods

 Linear (Image.BILINEAR): Uses a weighted average of the 2x2 neighborhood pixels.

o Advantages: Fast, smoother than nearest neighbor.

o Disadvantages: Less sharp, may produce blurry results.

 Bicubic (Image.BICUBIC): Uses a 4x4 neighborhood of pixels for interpola on.

o Advantages: Smoother and sharper images.

o Disadvantages: Slower than Bilinear, can introduce ringing ar facts.

 Bilinear (Image.BILINEAR): Computes the weighted average of a 2x2 pixel grid.

o Advantages: Faster than Bicubic.

o Disadvantages: So er, some mes blurrier.

 Lanczos (Image.LANCZOS): Uses a high-quality filter for downsampling, considering a larger


neighborhood of pixels.

o Advantages: High-quality results, reduces aliasing.

o Disadvantages: Slow, can introduce ringing ar facts.

Resizing Example (Custom Sampling)

import numpy as np

from PIL import Image

def image_sampling_custom(image_path, target_height, target_width):

# Open the original image

original_image = Image.open(image_path)
original_image_array = np.array(original_image)

# Calculate scale factors for width and height

scale_h = original_image.height / target_height

scale_w = original_image.width / target_width

# Create an empty array for the resized image

resized_image_array = np.zeros((target_height, target_width, original_image_array.shape[2]),


dtype=np.uint8)

# Loop over every pixel in the target image

for i in range(target_height):

for j in range(target_width):

orig_x = int(j * scale_w)

orig_y = int(i * scale_h)

resized_image_array[i, j] = original_image_array[orig_y, orig_x]

# Convert the resized image array back to an Image object

resized_image = Image.fromarray(resized_image_array)

return resized_image

# Example usage:

image_path = "image.jpg"

target_height = 100

target_width = 100

# Resizing the image using the custom sampling method

resized_image = image_sampling_custom(image_path, target_height, target_width)


# Save and show the resized image

resized_image.save("custom_resized_image.jpg")

resized_image.show()

Quan za on of Images

Quan za on reduces the number of colors or intensity levels in an image.

def quan ze_image_user_defined(img, num_levels):

gray_img = img.convert("L")

img_array = np.array(gray_img)

step_size = 256 // num_levels

quan zed_array = (img_array // step_size) * step_size

quan zed_img = Image.fromarray(quan zed_array.astype(np.uint8))

return quan zed_img

Image Connec vity (N4 and N8)

 N4 (4-connected): Refers to the set of 4 immediate neighboring pixels in a grid (up, down,
le , right).

 N8 (8-connected): Includes the set of 8 neighboring pixels, including diagonals.

img_array = np.random.randint(0,255, size=(10,10))

Adjacency Example (N4 and N8 Connec vity)

def m_adj(x1, y1, img):

n4p = n4(img, x1, y1) # Get N4 neighbors

ndp = nd(img, x1, y1) # Get N8 neighbors

m_adj_pixels = []

for i in range(max(0, x1-10), min(img.width, x1+10)):

for j in range(max(0, y1-10), min(img.height, y1+10)):

pixel_value = img.getpixel((i, j))

if (pixel_value in n4p) or (pixel_value in ndp and np.intersect1d(n4p, n4(img, i, j)) and all(val is
not None and val not in range(256) for val in np.intersect1d(n4p, n4(img, i, j)))):

m_adj_pixels.append((i, j))
return m_adj_pixels

You might also like