Question

In: Computer Science

python: modify an image (just show me how to write the two functions described below) 1.One...

python: modify an image (just show me how to write the two functions described below)

1.One way to calculate the contrast between two colours is to calculate the brightness of the top pixel (the average of the red, green and blue components, with all three components weighted equally), and subtract the brightness of the pixel below it. We then calculate the absolute value of this difference. If this absolute value is greater than a threshold value, the contrast between the two pixels is high, so we change the top pixel's colour to black; otherwise, the contrast between the two pixels is low, so we change the top pixel's colour to whiteDevelop a filter named detect_edges that returns a copy of an image, in which the copy has been modified using the edge detection technique described in the preceding paragraphs. This filter has two parameters: an image and a threshold, which is a positive number.

2.As before, we calculate the contrast of two pixels by subtracting the brightness values of the pixels and calculating the absolute value of the difference. We change a pixel's colour to black only if the contrast between the pixel and the one below it is high (i.e., the absolute value of the difference exceeds the filter's threshold attribute) or the contrast between the pixel and the one to the right of it is high. Otherwise, we change the pixel's colour to white.


  1. A simple algorithm for performing edge detection is: for every pixel that has a pixel below it, check the contrast between the two pixels. If the contrast is high, change the top pixel's colour to black, but if the contrast is low, change the top pixel's colour to white. For the bottom row (which has no pixels below it), simply set the pixel to white.

Solutions

Expert Solution

The below code modifies the original image using the two ways that has been specified in the question. I have used .shape[0] or .shape[1] to access the number of rows or columns in the image respectively. Also, I have created a copy of the original image by storing it in the imgCopy object and then manipulating the copy object.

For the first case we only check if the below pixel exists or not, if yes we find the absolute difference and then modify based on the difference else we set to white. For the second case, we check for the bottom pixel, if the pixel is modified there then we do not consider the right pixel (as flag is already true), and if it is modified in the right pixel then we do not modify in the final case. Please refer to comments in the code to understand it better.

CODE:-

import cv2 #to use the image processing capabilities in python

#Function that detects the edges by onyl analysing the below pixel (if present)

def detect_edges(img, threshold):

    imgCopy = img #store a copy of the original image

    #Traverse the image

    for posX in range(0, imgCopy.shape[0]):

        for posY in range(imgCopy.shape[1]):

            pxTop = imgCopy[posX, posY] #store the top pixel

            if(posX + 1 < imgCopy.shape[0]): #check if the bottom pixel is inside the image or not

                pxBot = imgCopy[posX + 1, posY] #store the bottom pixel

                avgTop = (int(pxTop[0]) + int(pxTop[1]) + int(pxTop[2]))/3 #take the average of the top pixel by weighing the red, green and blue pixel equally

                avgBot = (int(pxBot[0]) + int(pxBot[1]) + int(pxBot[2]))/3 #take the average of the bottom pixel by weighing the red, green and blue pixel equally

                if(abs(avgTop - avgBot) > threshold): #difference is greater than threshold

                    imgCopy[posX, posY] = [0, 0, 0] #assign black to the top pixel

                else: #assign white to the top pixel

                    imgCopy[posX, posY] = [255, 255, 255]

            else:

                imgCopy[posX, posY] = [255, 255, 255] #in all the other cases assign white to the top pixel

    return imgCopy #return the copy of image

#Function that detects the edges by analysing the below pixel or the right pixel (if present)

def detect_edgesRight(img, threshold):

    imgCopy = img  # store a copy of the original image

    #Traverse the image

    for posX in range(0, imgCopy.shape[0]):

        for posY in range(imgCopy.shape[1]):

            pxTop = imgCopy[posX, posY]  # store the top pixel

            flag = False #to store if the pixel is modified or not, if yes then we do not assign white else we do

            # check if the bottom pixel is inside the image or not

            if(posX + 1 < imgCopy.shape[0]):

                pxBot = imgCopy[posX + 1, posY]  # store the bottom pixel

                # take the average of the top pixel by weighing the red, green and blue pixel equally

                avgTop = (int(pxTop[0]) + int(pxTop[1]) + int(pxTop[2]))/3

                # take the average of the bottom pixel by weighing the red, green and blue pixel equally

                avgBot = (int(pxBot[0]) + int(pxBot[1]) + int(pxBot[2]))/3

                if(abs(avgTop - avgBot) > threshold):  # difference is greater than threshold

                    # assign black to the top pixel

                    imgCopy[posX, posY] = [0, 0, 0]

                    flag = True

            

            #check for the right pixel only if the pixel is not modified already i.e. flag = False

            if(posY + 1 < imgCopy.shape[1] and not flag):

                pxRight = imgCopy[posX, posY+1]  # store the right pixel

                # take the average of the left pixel by weighing the red, green and blue pixel equally

                avgTop = (int(pxTop[0]) + int(pxTop[1]) + int(pxTop[2]))/3

                # take the average of the right pixel by weighing the red, green and blue pixel equally

                avgRight = (int(pxRight[0]) + int(pxRight[1]) + int(pxRight[2]))/3

                if(abs(avgTop - avgRight) > threshold):  # difference is greater than threshold

                    # assign black to the left pixel

                    imgCopy[posX, posY] = [0, 0, 0]

                    flag = True #set flag to True as pixel is modified

            if(not flag): #if pixel is not still modified by any case

                imgCopy[posX, posY] = [255, 255, 255] #set to the pixel

    return imgCopy  # return the copy of image

img = cv2.imread("image.jpg")

cv2.imshow("Original", img)

cv2.imshow("Modified Image - Considering Only Below ", detect_edges(img, 5))

cv2.imshow("Modified Image - Considering Below & Right", detect_edgesRight(img, 5))

cv2.waitKey(0)

OUTPUT:-

The first image is the original image, the second image is the modified image using the first question and the last image is the image considering the below or right pixel.

Hope the answer helps you! Feel free to ask questions in comments and if the answer helped, please upvote!


Related Solutions

Language Python with functions and one main function Write a program that converts a color image...
Language Python with functions and one main function Write a program that converts a color image to grayscale. The user supplies the name of a file containing a GIF or PPM image, and the program loads the image and displays the file. At the click of the mouse, the program converts the image to grayscale. The user is then prompted for a file name to store the grayscale image in.
Python 3 Forming Functions Define and complete the functions described below. * function name: say_hi *...
Python 3 Forming Functions Define and complete the functions described below. * function name: say_hi * parameters: none * returns: N/A * operation: just say "hi" when called. * expected output: >>> say_hi() hi * function name: personal_hi * parameters: name (string) * returns: N/A * operation: Similar to say_hi, but you should include the name argument in the greeting. * expected output: >>> personal_hi("Samantha") Hi, Samantha * function name: introduce * parameters: name1 (string) name2 (string) * returns: N/A...
Python 3 Functions that give answers Define and complete the functions described below. * function name:...
Python 3 Functions that give answers Define and complete the functions described below. * function name: get_name * parameters: none * returns: string * operation: Here, I just want you to return YOUR name. * expected output: JUST RETURNS THE NAME...TO VIEW IT YOU CAN PRINT IT AS BELOW >>> print(get_name()) John * function name: get_full_name * parameters: fname (string) lname (string) first_last (boolean) * returns: string * operation: Return (again, NOT print) the full name based on the first...
''' Problem 1: Formin' Functions Define and complete the functions described below. The functions are called...
''' Problem 1: Formin' Functions Define and complete the functions described below. The functions are called in the code at the very bottom. So you should be able simply to run the script to test that your functions work as expected. ''' ''' * function name: say_hi * parameters: none * returns: N/A * operation: Uhh, well, just say "hi" when called. And by "say" I mean "print". * expected output: >>> say_hi() hi ''' ''' * function name: personal_hi...
''' Problem 1: Formin' Functions Define and complete the functions described below. The functions are called...
''' Problem 1: Formin' Functions Define and complete the functions described below. The functions are called in the code at the very bottom. So you should be able simply to run the script to test that your functions work as expected. ''' ''' * function name: say_hi * parameters: none * returns: N/A * operation: Uhh, well, just say "hi" when called. And by "say" I mean "print". * expected output: >>> say_hi() hi ''' ''' * function name: personal_hi...
PYTHON: Write a script that imports the functions in the module below and uses all of...
PYTHON: Write a script that imports the functions in the module below and uses all of the functions. import math def _main():     print("#" * 28, "\n", "Testing...1, 2, 3...testing!\n", "#" * 28, "\n", sep="")     f = -200     print("{:.2f} F is {:.2f} C".format(f, f2c(f)))     f = 125     print("{:.2f} F is {:.2f} C".format(f, f2c(f)))     c = 0     print("{:.2f} C is {:.2f} F".format(c, c2f(c)))     c = -200     print("{:.2f} C is {:.2f} F".format(c, c2f(c))) def f2c(temp):     #Converts Fahrenheit tempature to Celcius     if temp <...
Problem: Write a C++ program that will implement and test the five functions described below that...
Problem: Write a C++ program that will implement and test the five functions described below that use pointers and dynamic memory allocation. The Functions: You will write the five functions described below. Then you will call them from the main function, to demonstrate their correctness. 1. minimum: takes an int array and the array's size as arguments. It should return the minimum value of the array elements. Do not use square brackets anywhere in the function, not even the parameter...
Write a Python program to implement one studied entropy coding method, including two separate functions for...
Write a Python program to implement one studied entropy coding method, including two separate functions for encoding and decoding. Use the lyrics of your favorite song as the message to be processed, and test the program on the message. Include the source code, and detail the program design and execution procedure in this section.
Python: How would I modify the class below that takes a string and returns an object...
Python: How would I modify the class below that takes a string and returns an object holding a valid NANP phone number. I am asked to filll in the three methods listed, but underfined, below: __str__(), area_code(), and normalize(). My task is to clean up differently formatted telephone numbers by removing punctuation, such as '(', '-', and the like, and removing and the country code (1) if present. I am asked to start by stripping non-digits, and then see if...
Use Python for this quetions: Write a python functions that use Dictionary to: 1) function name...
Use Python for this quetions: Write a python functions that use Dictionary to: 1) function name it addToDictionary(s,r) that take a string and add it to a dictionary if the string exist increment its frequenc 2) function named freq(s,r) that take a string and a record if the string not exist in the dictinary it return 0 if it exist it should return its frequancy.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT