We use image processing to help computers understand and change pictures. This is the first step to teach computers to see like humans.
0
0
First image processing program in Computer Vision
Introduction
You want to open and show a picture on your computer.
You need to change a picture to black and white.
You want to resize a photo to fit on a website.
You want to find simple details like edges or colors in a picture.
Syntax
Computer Vision
import cv2 # Load an image from file image = cv2.imread('path_to_image.jpg') # Show the image in a window cv2.imshow('Image Window', image) cv2.waitKey(0) cv2.destroyAllWindows()
Use cv2.imread() to load an image from your computer.
cv2.imshow() opens a window to display the image. cv2.waitKey(0) waits for a key press to close the window.
Examples
This loads a color image and shows it in a window.
Computer Vision
import cv2 # Load and show a color image image = cv2.imread('flower.jpg') cv2.imshow('Color Image', image) cv2.waitKey(0) cv2.destroyAllWindows()
This loads the same image but in black and white.
Computer Vision
import cv2 # Load image in grayscale (black and white) gray_image = cv2.imread('flower.jpg', cv2.IMREAD_GRAYSCALE) cv2.imshow('Grayscale Image', gray_image) cv2.waitKey(0) cv2.destroyAllWindows()
This makes the image smaller and shows it.
Computer Vision
import cv2 # Resize image to half its size image = cv2.imread('flower.jpg') small_image = cv2.resize(image, (image.shape[1]//2, image.shape[0]//2)) cv2.imshow('Small Image', small_image) cv2.waitKey(0) cv2.destroyAllWindows()
Sample Model
This program loads a color image, changes it to black and white, shows both, and prints their sizes.
Computer Vision
import cv2 # Load an image image = cv2.imread('flower.jpg') # Convert to grayscale gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Show original and grayscale images cv2.imshow('Original Image', image) cv2.imshow('Grayscale Image', gray_image) cv2.waitKey(0) cv2.destroyAllWindows() # Print image shapes print(f'Original image shape: {image.shape}') print(f'Grayscale image shape: {gray_image.shape}')
OutputSuccess
Important Notes
Make sure the image file path is correct or the program will not load the image.
Color images have 3 channels (blue, green, red), grayscale has 1 channel.
Use cv2.destroyAllWindows() to close all image windows properly.
Summary
Image processing lets computers open and change pictures.
Use OpenCV functions like imread, imshow, and cvtColor to work with images.
Showing images and printing their size helps understand what the program does.