Image Processing Without OpenCV | python

| | | | | | | | | | | | | | | | | |

👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!

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:

# using matplotlib and numpy

import matplotlib.image as img

import numpy as npy


# provide image location readable

m = img.imread ( "taj.png" );


# defining the length of the original image

w, h = m.shape [: 2 ];


# xNew and yNew are the new width and
# image height required
after scaling

xNew = int (w * 1 / 2 );

yNew = int (h * 1 / 2 );


# calculate the scaling factor
# work more than 2 pixels

xScale = xNew / (w - 1 );

yScale = yNew / (h - 1 );


# using numpy, taking the xNew matrix
# width and new height with
# 4 attributes [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 image after scaling

img.imsave ( ’scaled.png’ , newImage);

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:

Grayscale image program:

# using NumPy

import numpy as npy


# using matplotlib

import matplotlib.image as img


# use statistics to import average
# to calculate average

from statistics import mean

m = img.imread ( "taj.png" )


# define the width and height of the original image

w, h = m.shape [: 2 ]


# new image dimension with 4 attributes per pixel

newImage = npy.zeros ([w, h, 4 ])

print (w)

print (h)

for i in range (w):

for j in range (h):

# RGB ratio 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 must be 1


# Save image with imsave

img.imsave ( ’grayedImage.png’ , newImage)

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:

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:

👻 Read also: what is the best laptop for engineering students?

Image Processing Without OpenCV | python __del__: Questions

How can I make a time delay in Python?

5 answers

I would like to know how to put a time delay in a Python script.

2973

Answer #1

import time
time.sleep(5)   # Delays for 5 seconds. You can also use a float value.

Here is another example where something is run approximately once a minute:

import time
while True:
    print("This prints once a minute.")
    time.sleep(60) # Delay for 1 minute (60 seconds).

2973

Answer #2

You can use the sleep() function in the time module. It can take a float argument for sub-second resolution.

from time import sleep
sleep(0.1) # Time in seconds

Image Processing Without OpenCV | python __del__: Questions

How to delete a file or folder in Python?

5 answers

How do I delete a file or folder in Python?

2639

Answer #1


Path objects from the Python 3.4+ pathlib module also expose these instance methods:

We hope this article has helped you to resolve the problem. Apart from Image Processing Without OpenCV | python, check other __del__-related topics.

Want to excel in Python? See our review of the best Python online courses 2023. If you are interested in Data Science, check also how to learn programming in R.

By the way, this material is also available in other languages:



Oliver Jackson

Tallinn | 2023-03-22

Maybe there are another answers? What Image Processing Without OpenCV | python exactly means?. Will get back tomorrow with feedback

Olivia Emmerson

Tallinn | 2023-03-22

Maybe there are another answers? What Image Processing Without OpenCV | python exactly means?. I am just not quite sure it is the best method

Angelo Wu

Warsaw | 2023-03-22

I was preparing for my coding interview, thanks for clarifying this - Image Processing Without OpenCV | python in Python is not the simplest one. I just hope that will not emerge anymore

Shop

Gifts for programmers

Learn programming in R: courses

$FREE
Gifts for programmers

Best Python online courses for 2022

$FREE
Gifts for programmers

Best laptop for Fortnite

$399+
Gifts for programmers

Best laptop for Excel

$
Gifts for programmers

Best laptop for Solidworks

$399+
Gifts for programmers

Best laptop for Roblox

$399+
Gifts for programmers

Best computer for crypto mining

$499+
Gifts for programmers

Best laptop for Sims 4

$

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

1947 answers

PythonStackOverflow

Check if one list is a subset of another in Python

1173 answers

PythonStackOverflow

How to specify multiple return types using type-hints

1002 answers

PythonStackOverflow

Printing words vertically in Python

909 answers

PythonStackOverflow

Python Extract words from a given string

798 answers

PythonStackOverflow

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

606 answers

PythonStackOverflow

Python os.path.join () method

384 answers

PythonStackOverflow

Flake8: Ignore specific warning for entire file

360 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically