Digital Image Processing is a significant aspect of data science. It is used in image modification and enhancement so that image attributes can be acquired to lead to a greater understanding of data.
An image is made up of elements called pixels. They are arranged in a two-dimensional manner, and are represented using squares.
There are three main types of images:
Negative transformation refers to subtracting pixel values from , where L is the maximum possible value of the pixel, and replacing it with the result.
To negatively transform an image, we loop through the pixels using two for
loops. If the image is RGB, the red, green, and blue values are subtracted from and the result is stored in place of the values. In the case of greyscale images, the intensity of the pixels is subtracted instead.
Negative transformation is done to bring attention to detail in the darker regions of the image.
The code below performs the negative transformation process exactly as described earlier:
import PIL #negative transformation function def neg_trans(img): #get width and height of image width,height=img.size #traverse through pixels for x in range(width): for y in range(height): pixel_color=img.getpixel((x,y)) #if image is RGB, subtract individual RGB values if type(pixel_color) == tuple: #s=(L-1)-r red_pixel=256-1-pixel_color[0] green_pixel=256-1-pixel_color[1] blue_pixel=256-1-pixel_color[2] #replace the pixel img.putpixel((x,y),(red_pixel,green_pixel,blue_pixel)) #if image is greyscale, subtract pixel intensity else: #s=(L-1)-r pixel_color=256-1-pixel_color #replace the pixel img.putpixel((x,y),pixel_color) return img
The neg_trans
function in the code above takes in an image as a parameter and traverses through its pixels.
The PIL
library provides the function getpixel()
, which returns the colour of the pixel present at a point, and putpixel()
, which plots a pixel of specified color at a point.
The colour of the pixels are stored in line and checked to see if they have the data type tuple
or int
.
tuple
means the pixel has three color channels, and the image is RGB.int
means the pixel has only one color channel, and the image is grayscale.If the image is RGB, the image is transformed by subtracting the respective color intensities of each pixel from , while for grayscale images, the singular intensity is subtracted from to obtain the negatively transformed image.
The putpixel()
function is then used to plot the negatively transformed pixels in place of the original pixels, as you can see in lines and .
RELATED TAGS
CONTRIBUTOR
View all Courses