In: Computer Science
Write code in Python:
The edge-detection function (detectEdges) described in Chapter 7 and shown below returns a black and white image. Think of a similar way to transform color values so that the new image is still in its original colors but the outlines within it are merely sharpened.
Then, define a function named sharpen that performs this operation. The function should expect an image and two integers as arguments. One integer should represent the degree to which the image should be sharpened. The other integer should represent the threshold used to detect edges.
(Hint: A pixel can be darkened by making its RGB values smaller.)
Example:
def detectEdges(image, amount):
"""Builds and returns a new image in which
the edges of
the argument image are highlighted and the
colors are
reduced to black and white."""
def average(triple):
(r, g, b) =
triple
return (r + g + b)
// 3
blackPixel = (0, 0, 0)
whitePixel = (255, 255, 255)
new = image.clone()
for y in range(image.getHeight() -
1):
for x in range(1,
image.getWidth()):
oldPixel
= image.getPixel(x, y)
leftPixel
= image.getPixel(x - 1, y)
bottomPixel
= image.getPixel(x, y + 1)
oldLum
= average(oldPixel)
leftLum
= average(leftPixel)
bottomLum
= average(bottomPixel)
if
abs(oldLum - leftLum) > amount or \
abs(oldLum
- bottomLum) > amount:
new.setPixel(x,
y, blackPixel)
else:
new.setPixel(x,
y, whitePixel)
return new
# Hey buddy, I have spent a lot of time on it, so if you got something from it, please give an upvote
# importing files
import time
import os
import sys
import math
import matplotlib.pyplot as plt
import numpy as np
import cv2
from PIL import Image, ImageOps
import numpy as np
import matplotlib.pyplot as plt
import numpy as np
def average(triple):
(r, g, b) = triple
u = (r + g + b)
return (u)
def detectEdges(image, amount):
h, w, c = image.shape
blackPixel = (0, 0, 0)
whitePixel = (255, 255, 255)
new = image
average(image[1,1])
for y in range(h - 1):
for x in range(1, w):
oldPixel = image[x,y]
leftPixel = image[x-1,y]
bottomPixel = image[x,y+1]
oldLum = average(oldPixel)
leftLum = average(leftPixel)
bottomLum = average(bottomPixel)
if abs(oldLum - leftLum) > amount or abs(oldLum - bottomLum) > amount:
new[x,y] = blackPixel
else:
new[x,y] = whitePixel
return new
ImagePath = "E:\\saga.jpg"
image = cv2.imread(ImagePath)
plt.figure()
plt.axes()
plt.subplot(1, 2, 1)
plt.imshow(image)
plt.title("Original Image")
NewImg = detectEdges(image,10)
plt.subplot(1, 2, 2)
plt.imshow(NewImg)
plt.title("Sharpened Image")
plt.show()
The output will display as sharpen picture as shown below: