'Low pass filter with apply function - Help to solve
I have a question.how can I write the code.
I want to create an image interface. The class filter should apply a low-pass filter to a given image and should be derived from an abstract base class Image. The filter class holds a 1D array with 3 elements which are used as the filter kernel for 1D filter operation. However, the apply_1D method is applied two times and it stores the intermediate result in a transposed image ( with rows and columns interchanged). I should use value 0 if values outside my image need to be accessed and the image is stored row-major, all pixels of the first row, then all pixels of the second row, and another thing it is required to pair a row and column, or a pair of height and width in order ( row first, then column).
input image First rows 0, 0, 0,0, 0 Second row 0, 0, 0, 0, 0 third row 0, 0, 1, 0, 0 fourth row 0, 0, 0, 0, 0 fifth row 0, 0,0 ,0, 0 the output image is :
input image First rows 0 , 0 , 0 , 0 , 0 Second row 0 , 0.0625 , 0.125 , 0.0625 , 0 third row 0 , 0.125 , 0.25 , 0.125, 0 fourth row 0 , 0.625 , 0.125 , 0.0625 , 0 fifth row 0 , 0 ,0 , 0, 0
import os
class Filter:
kernel = [0.25, 0.5, 0.25]
def apply(self, img: InterfaceImage) -> InterfaceImage:
return self._apply_1d(self._apply_1d(img))
def _apply_1d(self, in_img: InterfaceImage) -> InterfaceImage:
new_height = in_img.width
new_width = in_img.height
out_transposed = Image(new_height, new_width, [0] * new_height * new_width)
height = in_img.height
width = in_img.width
for row in range(height):
for col in range(width):
filtered = (
Filter.kernel[0] * in_img.get(row, col - 1)
+ Filter.kernel[1] * in_img.get(row, col)
+ Filter.kernel[2] * in_img.get(row, col + 1)
)
# HINT: The set method always takes row first, column second. It is called with
# 'col, row' below because 'out_transposed' is a transposed image.
out_transposed.set(col, row, filtered)
return out_transposed
def to_string(image: InterfaceImage) -> str:
result = ""
for row in range(image.height):
for col in range(image.width):
result += "{:.5f} ".format(image.get(row, col))
result += "\n"
return result
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
height_and_width = input()
height, width = (int(item) for item in height_and_width.split())
data = []
for _ in range(height):
for value in input().split():
data.append(float(value))
filter = Filter()
image = Image(height=height, width=width, data=data)
filtered_image = filter.apply(image)
result = to_string(filtered_image)
fptr.write(result + '\n')
fptr.close()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|