Skip to content

Commit 7742536

Browse files
AtharvMalusarepre-commit-ci[bot]cclauss
authored
Intensity_based_Segmentation (#12491)
* Add files via upload * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update intensity-based_segmentation.py * Update and rename intensity-based_segmentation.py to intensity_based_segmentation.py * Update intensity_based_segmentation.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Apply suggestions from code review * [0, 1, 1]], dtype=int32) --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent f24ddba commit 7742536

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
# Source: "https://www.ijcse.com/docs/IJCSE11-02-03-117.pdf"
2+
3+
# Importing necessary libraries
4+
import matplotlib.pyplot as plt
5+
import numpy as np
6+
from PIL import Image
7+
8+
9+
def segment_image(image: np.ndarray, thresholds: list[int]) -> np.ndarray:
10+
"""
11+
Performs image segmentation based on intensity thresholds.
12+
13+
Args:
14+
image: Input grayscale image as a 2D array.
15+
thresholds: Intensity thresholds to define segments.
16+
17+
Returns:
18+
A labeled 2D array where each region corresponds to a threshold range.
19+
20+
Example:
21+
>>> img = np.array([[80, 120, 180], [40, 90, 150], [20, 60, 100]])
22+
>>> segment_image(img, [50, 100, 150])
23+
array([[1, 2, 3],
24+
[0, 1, 2],
25+
[0, 1, 1]], dtype=int32)
26+
"""
27+
# Initialize segmented array with zeros
28+
segmented = np.zeros_like(image, dtype=np.int32)
29+
30+
# Assign labels based on thresholds
31+
for i, threshold in enumerate(thresholds):
32+
segmented[image > threshold] = i + 1
33+
34+
return segmented
35+
36+
37+
if __name__ == "__main__":
38+
# Load the image
39+
image_path = "path_to_image" # Replace with your image path
40+
original_image = Image.open(image_path).convert("L")
41+
image_array = np.array(original_image)
42+
43+
# Define thresholds
44+
thresholds = [50, 100, 150, 200]
45+
46+
# Perform segmentation
47+
segmented_image = segment_image(image_array, thresholds)
48+
49+
# Display the results
50+
plt.figure(figsize=(10, 5))
51+
52+
plt.subplot(1, 2, 1)
53+
plt.title("Original Image")
54+
plt.imshow(image_array, cmap="gray")
55+
plt.axis("off")
56+
57+
plt.subplot(1, 2, 2)
58+
plt.title("Segmented Image")
59+
plt.imshow(segmented_image, cmap="tab20")
60+
plt.axis("off")
61+
62+
plt.show()

0 commit comments

Comments
 (0)