We know that OpenCV is widely used for working with images and has a wide range of functions for this. But what if we want to process image files without using any external library like OpenCV. Let’s see how we can do that.
Image scaling (using nearest neighbor interpolation):
Nearest neighbor interpolation — this is the easiest way to interpolate. This method simply determines the "closest" neighboring pixel and takes a value for its intensity.
Consider a small image whose width is w and the height is — h that we want to change from width p to width q, assuming p & gt; m and q & gt; n. Now we need two scaling constants:
scale_x = p / w scale_y = q / h
Now we simply iterate over all the pixels in the output image, referring to the original pixels we are copying from. scaling our control variables with scale_x and scale_y , and rounding the resulting scaled index values.
Visual representation:
The image is 3X3 pixels (9 pixels in total), now if we want to increase the image size to 6X6, then according to the nearest neighboring algorithm 6/3 (i.e. 2) pixels should have the same RGB value as the value pixel to the original image.
Image scaling program:
|
Output:
Grayscale the image:
Using the mean value method, this method emphasizes the intensity of a pixel, rather than showing what RGB values ‚Äã‚Äãit is composed of. When we calculate the average RGB value and assign it the RGB value for a pixel, since the RGB value of the pixel is the same, it will not be able to create any color, since all colors are generated due to a different ratio of RGB values, since in this case the ratio would be 1: 1: 1. Therefore, the rendered image will look like a gray image.
Visual representation:
![](http://espressocode.top/images/manmolisamyrdlea502867.jpg)
Grayscale image program:
|
Output:
Cropping an image:
Cropping basically removes unwanted pixel. This can be done by placing the required pixel in another grid of images, the size of which matches the required after cropping.
Consider an image with a size of 10 √ó 10 pixels, and if we only want to crop the center of an image with a size of 4 √ó 4 pixels, then we need to collect pixel values ‚Äã‚Äãfrom (10-4) / 2, starting at (3, 3) up to 4 pixels in the x direction and 4 pixels in the y direction .
Visual representation:
![](http://espressocode.top/images/henlulunsisymfoo626598.jpg )
Image cropper:
# using matplotlib and numpy
import
matplotlib.image as img
import
numpy as npy
# read image in variable m
m
=
img.imread (
"taj.png"
)
# definition of image size 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 source image height
print
(w)
print
(h)
for
i
in
range
(
1
, xNew):
for
j
in
range
(
1
, yNew):
# crop from 100 to 100 pixels of the original image
newImage [i, j]
=
m [
100
+
i,
100
+
j]
# save the image
img.imsave (
’cropped.png’
, newImage)
Output: