USE PYTHON 3 ONLY!!! Create a program to turn a color picture into a grayscale p
ID: 3699051 • Letter: U
Question
USE PYTHON 3 ONLY!!!
Create a program to turn a color picture into a grayscale picture. Name the file you create 305.py
Create a function which accepts an Image and returns a grayscale version of the image. The original image should not be changed.
Both images need to be the same size. However, you will be creating the second grayscale image so be sure to make it the same size as the original.
Create a main function which asks the user which file they wish load. Then use the function you have written to create a grayscale version. Save the grayscale version to a file.
Optional: The filename (used to save) should represent both the original filename as well as the word grayscale. An example is ‘BSU.gif’ is saved as ‘BSUgrayscale.gif’
Make sure to turn in your resulting file.
Explanation / Answer
#maintain indentation
import cv2
# save this file as 305.py or RGB2Gray.py
#make sure opencv2 is installed in your system
# without opencv2 not installed in your system
# you cant do anythig with images
def convertImage(fn):
# this function is to convert the given image
# into a grayscale image
# and return the image object
ext = fn[fn.find(".")+1:] #extracting the extention form the file name
# extention will be after '.' obviously
image = cv2.imread(fn) # reading the image
gray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)# this is main function to convert
temp_fname=fn+"grayscale."+ext # to store the new file (it just newfile's name with ext)
cv2.imwrite(temp_fname,gray_img) # writing the converted image into a new image file
return gray_img # returning the wanted newly created image object
def main():
print(" *********Rules**********")
print(" 1.Enter Image File name with full extention")
print(" 2.Ex:img.png or img.jpg");
print(" 3.Make sure that this python source file and the image file you want to convert are in same directory")
print(" 4.Make sure you are entering only a image file only");
print(" 5.Otherwise exceptions will occur!");
file_name=input("Enter The File with extention : ");
gray_img = convertImage(file_name) # now you have the imageobject in gray_img var
print("Image Converted Successfully")
print("Check the Same directory!");
main(); #calling the main function
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.