[๐Ÿ“ท] Tinkering with images #2

Prerequisites

Go through the previous article of this thread: [๐Ÿ“ท] Tinkering with images #1

Introduction

In my previous post, I covered some basic operations that I was able to perform on images using OpenCV, such as, capturing an image from my laptop’s webcam & storing its pixel values in a file.

Since it became clear to me, that, a digital image of N*M dimensions is basically a multi-dimensional array with N rows and M columns, where each element of the array is called a pixel where each pixel is an array of three elements denoting intensity values for red, green & blue pixels, ranging between 0 & 255. The above description can be shown in the image below:

Keeping the above description in mind, I decided to work on the following:

  1. Generation of “pseudo-random images” or basically images where the value of each pixel’s element is generated using Python’s pseudo-random integer generating function, random.randint().
  2. Next, I decided to work on something similar: Rather than selecting a random integer value b/w 0-255, the program would select a random prime number from prime numbers b/w 0-255. I wanted to check whether there was any significant difference between the two.

Program #1: Generating a pseudo-random image

Explanation: Basically, the entire program can be broken down into three functions:

1. generateRandomPixel() : This function generates individual pixels of an image where the value for red, green & blue pixels is generated using the random.randInt(0,255) method, which returns a pseudo-random integer between 0 & 255. The output of this function can be described as [random.randInt(0,255), random.randInt(0,255), random.randInt(0,255)]. Here is the code for the above-mentioned function:

#GENERATING PSEUDO-RANDOM IMAGES

#IMPORTING MODULES
import sys
import cv2
import random
import numpy

'''
    Function: GenerateRandomPixel()
    Functionality: Will generate a random pixel
    Parameter(s): NILL
    Output: [R,G,B] list where R,G,B are random values between 0-255
'''
def generateRandomPixel():
    R = random.randint(0,255)
    G = random.randint(0,255)
    B = random.randint(0,255)
    return list([R,G,B])        #Returns a pixel list [R,G,B]

2. generateCol(ColSize): It returns a row of pixels with colSize length. The way this works is by simply calling the generateRandomPixel() method, where, colSize is the column size. The output of the above method is pushed into a temporary array which is returned back. The actual output looks like this: [[R1,G1,B1], ..... , [Ry,Gy,By]]. Here is the code for the above-mentioned function:

'''
    Function: generateCol()
    Functionality: Will generate a list storing y pixel values for an image with x*y resolution
    Parameter(s): ColSize - Will store the column size
    Output: [[R1,G1,B1], ..... , [Ry,Gy,By]] where Ri,Gi,Bi are random values between 0-255
'''
def generateCol(colSize):
    tempCol=[]
    for i in range(colSize):
        tempCol.append(generateRandomPixel())
    return list(tempCol)        #Returns a column list of pixel values for an image with x*y res.

3. generateRow(ColSize,RowSize): It returns an M*N array with each element of the array being a pixel, which is an array of 3 values. This is done by simply calling the generateCol(colSize), rowSize number of times. The only thing to keep in mind would be the generateRow method that will generate a list, but to convert this into an image, we would have to convert this list into a NumPy array, which can be achieved using the numpy.asarray() method which can be imported using the NumPy package.

'''
    Function: generateRow()
    Functionality: Will generate a list storing x columns (w/ y pixels) for an image with x*y resolution
    Parameters(x) : colSize - Will store the column size
                    rowSize - Will store the row size
    Output :
    [
        [[R11,G11,B11],...,[R1y,G1y,B1y]],
        .
        .
        [[Rx1,Gx1,Bx1],...,[Rxy,Gxy,Bxy]],
    ] where Ri,Gi,Bi will be random values between 0-255
'''
def generateRow(colSize,rowSize):
    tempRow=[]
    for i in range(rowSize):
        tempRow.append(generateCol(colSize))
    return list(tempRow)    #Returns a list which stores an image of x*y res.

'''
    Function: generateRandomImage(nameOfFile)
    Functionality: Will generate a random image & will store it in nameOfFile.FileType
    Parameter(s): nameOfFile (w/o file type)
'''
def generateRandomImage():
    nameOfFile = input("Name of file in which random image will be stored (w/o file type)?\t")
    colSize = int(input("Column size of an image?\t"))
    rowSize = int(input("Row size of an image?   \t"))
    nameOfFile += ".png"
    cv2.imwrite(nameOfFile,numpy.asarray(generateRow(ColSize,RowSize)))
    #numpy.asarray(listName) converted the image list into a numpy array for writing into an image using cv2.imwrite()


randomIngNum = int(input("Number of random images to be generated?\t"))
i = 0
while i<randomIngNum:
    generateRandomImage()
    i+=1

Output #1

Okay, so the above images look exactly like the old Cathode Ray Tube (CRT) television sets :

Image: A Cathode Ray Tube (CRT) Television

Program #2: Generating a pseudo-random image using prime integers

This program is the same as above, w/ the only difference being that the image is generated w/ the help of prime numbers. Here is the program below :

#Description: Generating a pseudorandom image with prime numbers
#Author(s)  : asxyzp

import cv2
import random
import numpy

PrimeArr = []                       #Will store prime numbers between 0-255

'''
    Name : CheckPrime(num)
    Utility : Checks whether the number num is prime
    Parameter(s) : num (a positive integer)
    return value : boolean (true : If num is prime, false : If num is not prime)
'''
def CheckPrime(num):
    if num<2:                       #0,1 aren't prime
        #print(num," is not prime\n")
        return False
    elif num==2:                    #2 is prime
        #print(num," is not prime\n")
        return True
    elif num>2:
        for i in range(2,num):
            if num%i==0:            #If num>2 & num is divisible by any number between 2 & num-1, then num isn't prime
                return False
        return True    

'''
    Name : GeneratePrimeArr()
    Utility : Generates & stores prime numbers between 0 & 255 in primeArr
    Parameter(s) : None
    Return value : None
'''
def GeneratePrimeArr():
    for i in range(0,256):
        if CheckPrime(i):           #Appends number if prime
            PrimeArr.append(i)

GeneratePrimeArr()                  #Generates an array of prime numbers

'''
    Function: GenerateRandomPixel()
    Functionality: Will generate a random pixel from PrimeArr list
    Parameter(s): NILL
    Output: [R,G,B] list where R,G,B are random prime values between 0-255
'''
def GenerateRandomPixel():
    R = random.choice(PrimeArr) #random.choice(PrimeArr) chooses random values from PrimeArr list
    G = random.choice(PrimeArr)
    B = random.choice(PrimeArr)
    return list([R,G,B])        #Returns a pixel's [R,G,B] list

'''
    Function: GenerateCol()
    Functionality: Will generate a list storing y pixel values for an image with x*y resolution
    Parameter(s): ColSize - Will store the column size
    Output: [[R1,G1,B1], ..... , [Ry,Gy,By]] where Ri,Gi,Bi are random prime values between 0-255
'''
def GenerateCol(ColSize):
    tempCol=[]
    for i in range(ColSize):
        tempCol.append(GenerateRandomPixel())
    return list(tempCol)        #Returns a column list of pixel values for an image with x*y res.

'''
    Function: GenerateRow()
    Functionality: Will generate a list storing x columns (w/ y pixels) for an image with x*y resolution
    Parameters(x) : ColSize - Will store the column size
                    RowSize - Will store the row size
    Output :
    [
        [[R11,G11,B11],...,[R1y,G1y,B1y]],
        .
        .
        [[Rx1,Gx1,Bx1],...,[Rxy,Gxy,Bxy]],
    ] where Ri,Gi,Bi will be random prime values between 0-255
'''
def GenerateRow(ColSize,RowSize):
    tempRow=[]
    for i in range(RowSize):
        tempRow.append(GenerateCol(ColSize))
    return list(tempRow)    #Returns a list which stores an image of x*y res.

'''
    Function: GenerateRandomImage(NameOfFile)
    Functionality: Will generate a random image & will store it in NameOfFile.FileType
    Parameter(s): NameOfFile (w/o file type)
'''
def GenerateRandomImage(NameOfFile,ColSize,RowSize):
    NameOfFile += ".png"
    cv2.imwrite(NameOfFile,numpy.asarray(GenerateRow(ColSize,RowSize)))
    #numpy.asarray(listName) converted the image list into a numpy array for writing into an image using cv2.imwrite()


RandomIngNum = int(input("Number of random images to be generated?\t"))
i = 0
NameOfFile = input("Name of file in which random image will be stored (w/o file type)?\t")
ColSize = int(input("Column size of an image?\t"))
RowSize = int(input("Row size of an image?   \t"))
while i<RandomIngNum:
    GenerateRandomImage(NameOfFile+str(i+1),ColSize,RowSize)
    i+=1
print("Random prime images generated :)")

Output #2

The output of the above program is the same as that of the first program.

Summary

Hereโ€™s a small summary of all the different functions used in the program:

random.randInt(M,N): Returns a random integer between M & N.

numpy.asarray(list): Converts a list into an array.

Moving ahead, I got really curious about the frequency of the occurrence of the pixels in the above images, so I build a program to plot frequency using a python library called matplotlib. I would be covering this part in my next blog post. Bye for now.

My explorations have been captured in this Twitter thread

References

  1. https://numpy.org/doc/stable/reference/generated/numpy.asarray.html
  2. https://www.geeksforgeeks.org/python-randint-function/

One response to “[๐Ÿ“ท] Tinkering with images #2”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create your website with WordPress.com
Get started
%d bloggers like this: