From fc98961814faa8ebb58f349cdba4fdc265eae184 Mon Sep 17 00:00:00 2001 From: Tanay Karve Date: Fri, 16 Oct 2020 18:45:20 +0530 Subject: [PATCH] Hacktoberfest 2020: Added computer vision algorithm (#2946) * Create meanthresholding.py * Rename meanthresholding.py to meanthreshold.py * Update meanthreshold.py * Update computer_vision/meanthreshold.py Verified this part works, thanks. Co-authored-by: Christian Clauss * Update computer_vision/meanthreshold.py Co-authored-by: Christian Clauss Co-authored-by: Christian Clauss --- computer_vision/meanthreshold.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 computer_vision/meanthreshold.py diff --git a/computer_vision/meanthreshold.py b/computer_vision/meanthreshold.py new file mode 100644 index 0000000..7665793 --- /dev/null +++ b/computer_vision/meanthreshold.py @@ -0,0 +1,30 @@ +from PIL import Image + +""" +Mean thresholding algorithm for image processing +https://en.wikipedia.org/wiki/Thresholding_(image_processing) +""" + + +def mean_threshold(image: Image) -> Image: + """ + image: is a grayscale PIL image object + """ + height, width = image.size + mean = 0 + pixels = image.load() + for i in range(width): + for j in range(height): + pixel = pixels[j, i] + mean += pixel + mean //= width * height + + for j in range(width): + for i in range(height): + pixels[i, j] = 255 if pixels[i, j] > mean else 0 + return image + + +if __name__ == "__main__": + image = mean_threshold(Image.open("path_to_image").convert("L")) + image.save("output_image_path") -- GitLab