Skip to content

Hacktoberfest 2020: Added computer vision algorithm #2946

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Oct 16, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions computer_vision/meanthreshold.py
Original file line number Diff line number Diff line change
@@ -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
Comment on lines +14 to +20
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
mean = 0
pixels = image.load()
for i in range(width):
for j in range(height):
pixel = pixels[j, i]
mean += pixel
mean //= width * height
total = sum(sum(pixel for pixel in row) for row in image.load())
mean = total // (width * height)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes I tried using list builder comprehension initially. However image.load() returns a PixelAccess object which according to the documentation is not Iterable. Thus when running this code the following exception is thrown:
TypeError: 'PixelAccess' object is not iterable


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")