Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- File: sharpen.py
- Project 7.10
- Defines and tests a function to sharpen an image.
- """
- from images import Image
- def sharpen(image, degree, threshold):
- """Builds and returns a sharpened image. Expects an image
- and two integers (the degree to which the image should be sharpened and the
- threshold used to detect edges) as arguments."""
- def getDiff(colorVal1, colorVal2):
- """This auxiliary function calculates the difference between
- two tuples."""
- (r1, g1, b1) = colorVal1
- (r2, g2, b2) = colorVal2
- average1 = (r1 + g1 + b1) // 3
- average2 = (r2 + g2 + b2) // 3
- difference = average1 - average2
- return difference
- imageCopy = image.clone() # Get a copy of the original image
- height = imageCopy.getHeight() # Get image height
- width = imageCopy.getWidth() # Get image width
- # Step through the pixels in the function to detect the edges
- for y in range(height -1):
- for x in range(1, width):
- (r, g, b) = imageCopy.getPixel(x, y) # Get the color of the current pixel
- (rBottom, gBottom, bBottom) = image.getPixel(x, y + 1) # Get the color of the pixel underneath current
- (rLeft, gLeft, bLeft) = image.getPixel(x - 1, y) # Get the color of the pixel next to current
- # Compare the current pixel with the one underneath it.
- if abs(getDiff((r, g, b), (rBottom, gBottom, bBottom))) > threshold:
- tempColor = [r + degree, g + degree, b + degree] # Use a list to hold temporary colors, increased by degree
- bottom = [r - degree, g - degree, b - degree] # Degree is subtracted here, to increase contrast
- # Use a loop to check for out-of range colors:
- for index in range(len(tempColor)):
- if tempColor[index] > 255:
- tempColor[index] = 255
- if bottom[index] < 0:
- bottom[index] = 0
- tempColor[index] = tempColor[index] - bottom[index]
- # Set the new color for the pixels
- imageCopy.setPixel(x, y, tuple(tempColor))
- # Compare the current pixel with the one to its left
- elif abs(getDiff((r, g, b), (rLeft, gLeft, gLeft))) > threshold:
- tempColor = [r + degree, g + degree, b + degree]
- left = [r - degree, g - degree, b - degree]
- # Check for out-of-range colors
- for index in range(len(tempColor)):
- if tempColor[index] > 255:
- tempColor[index] = 255
- if left[index] < 0:
- left[index] = 0
- tempColor[index] = tempColor[index] - left[index]
- # Set the new color
- imageCopy.setPixel(x, y, tuple(tempColor))
- return imageCopy
- def main():
- filename = input("Enter the image file name: ")
- image = Image(filename)
- newimage = sharpen(image, 20, 15)
- newimage.draw()
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement