Skip to content

Commit 2030b33

Browse files
Update and rename intensity-based_segmentation.py to intensity_based_segmentation.py
1 parent 9d4ca70 commit 2030b33

File tree

2 files changed

+57
-63
lines changed

2 files changed

+57
-63
lines changed

computer_vision/intensity-based_segmentation.py

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

0 commit comments

Comments
 (0)