Image Processing without OpenCV | Python
Last Updated :
04 Jan, 2023
We know OpenCV is widely used to operate on images and has a wide spectrum of functions to do so. But what if we want to process the image files without using any external library like OpenCV. Let's see how can we do this.
Image Scaling (Using Nearest Neighbour Interpolation):
Nearest Neighbour interpolation is the simplest way of interpolation. This method simply determines the "nearest" neighboring pixel and assumes the intensity value of it.
Consider a small image which is ‘w’ pixels wide by ‘h’ pixels high, which we want to re-size to ‘p’ pixels wide by ‘q’ pixels high, assuming that p>m and q>n. Now, we need two scaling constants:
scale_x = p/w
scale_y = q/h
Now, we simply loop through all the pixels in the output image, addressing the source pixels to copy from by scaling our control variables by scale_x and scale_y, and rounding the resulting scaled index values.
Pictorial representation :
Image of 3X3 pixel (total 9 pixels), now if we want to increase the size of image up to 6X6 then, according to nearest neighboring algorithm 6/3 (i.e 2) pixels should have the same RGB value as that of the pixel in original Image.
Program for scaling an Image:
Python3
# using matplotlib and numpy
import matplotlib.image as img
import numpy as npy
# provide the location of image for reading
m = img.imread("taj.png");
# determining the length of original image
w, h = m.shape[:2];
# xNew and yNew are new width and
# height of image required
after scaling
xNew = int(w * 1 / 2);
yNew = int(h * 1 / 2);
# calculating the scaling factor
# work for more than 2 pixel
xScale = xNew/(w-1);
yScale = yNew/(h-1);
# using numpy taking a matrix of xNew
# width and yNew height with
# 4 attribute [alpha, B, G, B] values
newImage = npy.zeros([xNew, yNew, 4]);
for i in range(xNew-1):
for j in range(yNew-1):
newImage[i + 1, j + 1]= m[1 + int(i / xScale),
1 + int(j / yScale)]
# Save the image after scaling
img.imsave('scaled.png', newImage);
Output:
Gray Scaling of an Image:
Using the average value method, this method highlights the intensity of the pixel rather than showing what RGB values it consists. When we calculate the average value of RGB and assign It to RGB value of pixel, Since the RGB value of the pixel is same, it will not be able to create any color since all the colors are formed due different ratio of RGB value since in this case ratio will be 1:1:1. Hence Image then formed will look as gray Image.
Pictorial representation :
Program for Gray scaling an Image :
Python3
# using numpy
import numpy as npy
# using matplotlib
import matplotlib.image as img
# using statistics to import mean
# for mean calculation
from statistics import mean
m = img.imread("taj.png")
# determining width and height of original image
w, h = m.shape[:2]
# new Image dimension with 4 attribute in each pixel
newImage = npy.zeros([w, h, 4])
print( w )
print( h )
for i in range(w):
for j in range(h):
# ratio of RGB will be between 0 and 1
lst = [float(m[i][j][0]), float(m[i][j][1]), float(m[i][j][2])]
avg = float(mean(lst))
newImage[i][j][0] = avg
newImage[i][j][1] = avg
newImage[i][j][2] = avg
newImage[i][j][3] = 1 # alpha value to be 1
# Save image using imsave
img.imsave('grayedImage.png', newImage)
Output:
Cropping of an Image:
Cropping is basically removing the unwanted pixel. This can be done by taking required pixel in a different Image grid whose size is as required after cropping.
Consider an Image of size 10 X 10 pixel and if we require to crop only the center of image with 4 X 4 pixel then we need to collect the pixel values from (10-4)/2 starting from (3, 3) up to 4 pixel in x direction and 4 pixel in y direction.
Pictorial representation :
Program for cropping an Image :
Python3
# using matplotlib and numpy
import matplotlib.image as img
import numpy as npy
# reading image in variable m
m = img.imread("taj.png")
# determining dimension of image width(w) height(h)
w, h = m.shape[:2]
# required image size after cropping
xNew = int(w * 1 / 4)
yNew = int(h * 1 / 4)
newImage = npy.zeros([xNew, yNew, 4])
# print width height of original image
print(w)
print(h)
for i in range(1, xNew):
for j in range(1, yNew):
# cropping start from 100, 100 pixel of original image
newImage[i, j]= m[100 + i, 100 + j]
# save image
img.imsave('cropped.png', newImage)
Output:
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read