Skip to content

Commit 9f90f5b

Browse files
TanayKarvecclauss
andauthored
Hacktoberfest 2020: Added computer vision algorithm (TheAlgorithms#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 <[email protected]> * Update computer_vision/meanthreshold.py Co-authored-by: Christian Clauss <[email protected]> Co-authored-by: Christian Clauss <[email protected]>
1 parent c809e84 commit 9f90f5b

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

Diff for: computer_vision/meanthreshold.py

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
from PIL import Image
2+
3+
"""
4+
Mean thresholding algorithm for image processing
5+
https://en.wikipedia.org/wiki/Thresholding_(image_processing)
6+
"""
7+
8+
9+
def mean_threshold(image: Image) -> Image:
10+
"""
11+
image: is a grayscale PIL image object
12+
"""
13+
height, width = image.size
14+
mean = 0
15+
pixels = image.load()
16+
for i in range(width):
17+
for j in range(height):
18+
pixel = pixels[j, i]
19+
mean += pixel
20+
mean //= width * height
21+
22+
for j in range(width):
23+
for i in range(height):
24+
pixels[i, j] = 255 if pixels[i, j] > mean else 0
25+
return image
26+
27+
28+
if __name__ == "__main__":
29+
image = mean_threshold(Image.open("path_to_image").convert("L"))
30+
image.save("output_image_path")

0 commit comments

Comments
 (0)