im facing problem in sepaarte touching objects
import cv2
import numpy as np
import os
output_folder = r"E:grains_output"
# Create the folder if it doesn’t exist
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# Example: saving an image
img = cv2.imread(r"C:UsersDixuDownloadstest1.png") # your grain image
if img is None:
print("Error: Image not found! Check the path and filename.")
exit()
else:
print("Image loaded successfully!")
cv2.imwrite(os.path.join(output_folder, "segmented.png"), img)
# FUNCTION: Separate grains using COLOR segmentation (HSV
def separate_grains(image_path):
print("Loading:", image_path)
img = cv2.imread(image_path)
if img is None:
print("Error: image not found!")
return None, None
# Convert to HSV
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# Yellow grains range
lower = np.array([15, 40, 60])
upper = np.array([40, 255, 255])
# Mask grains
mask = cv2.inRange(hsv, lower, upper)
# Morphology cleanup
kernel = np.ones((5, 5), np.uint8)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel, iterations=3)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel, iterations=2)
# Convert mask to binary
ret, thresh = cv2.threshold(mask, 0, 255, cv2.THRESH_BINARY)
# Noise removal
kernel = np.ones((3, 3), np.uint8)
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2)
# Sure background area
sure_bg = cv2.dilate(opening, kernel, iterations=3)
# Sure foreground area
dist_transform = cv2.distanceTransform(opening, cv2.DIST_L2, 5)
ret, sure_fg = cv2.threshold(dist_transform, 0.6 * dist_transform.max(), 255, 0)
# Unknown region
sure_fg = np.uint8(sure_fg)
unknown = cv2.subtract(sure_bg, sure_fg)
# Marker labeling
ret, markers = cv2.connectedComponents(sure_fg)
markers = markers + 1 # background = 1
markers[unknown == 255] = 0
# Apply watershed
markers = cv2.watershed(img, markers)
mask[markers == -1] = 0 # boundaries
return mask, img
def save_grains(mask, img):
# print("Saving grains…")
output_dir = output_folder # Use the folder defined at the top
os.makedirs(output_dir, exist_ok=True)
# Find contours
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
grain_id = 1
for cnt in contours:
x, y, w, h = cv2.boundingRect(cnt)
if w < 10 or h < 10:
continue
grain = img[y:y + h, x:x + w]
filename = os.path.join(output_dir, f"grain_{grain_id}.png")
cv2.imwrite(filename, grain)
print("Saved:", filename)
grain_id += 1
print("nAll grains saved inside folder:", output_dir)
# Draw contours on a copy of the original image
result = img.copy()
cv2.drawContours(result, contours, -1, (0, 0, 255), 2)
# Save the segmented image
segmented_path = os.path.join(output_dir, "segmented_contours.png")
cv2.imwrite(segmented_path, result)
print("Segmented image with contours saved as:", segmented_path)
return result
# ———————————————————
# MAIN EXECUTION
# ———————————————————
if __name__ == "__main__":
# print("Current working directory:", os.getcwd())
mask, img = separate_grains(r"C:UsersDixuDownloadstest1.png")
if mask is not None:
result_img = save_grains(mask, img)
# # Show results
# cv2.namedWindow("Mask", cv2.WINDOW_NORMAL)
# cv2.resizeWindow("Mask", 600, 500)
# cv2.imshow("Mask", mask)
cv2.namedWindow("Segmented Image", cv2.WINDOW_NORMAL)
cv2.resizeWindow("Segmented Image", 600, 500)
cv2.imshow("Segmented Image", result_img)
cv2.waitKey(0)
cv2.destroyAllWindows()import cv2
import numpy as np
import os
output_folder = r"E:grains_output"
# Create the folder if it doesn’t exist
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# Example: saving an image
img = cv2.imread(r"C:UsersDixuDownloadstest1.png") # your grain image
if img is None:
print("Error: Image not found! Check the path and filename.")
exit()
else:
print("Image loaded successfully!")
cv2.imwrite(os.path.join(output_folder, "segmented.png"), img)
# FUNCTION: Separate grains using COLOR segmentation (HSV
def separate_grains(image_path):
print("Loading:", image_path)
img = cv2.imread(image_path)
if img is None:
print("Error: image not found!")
return None, None
# Convert to HSV
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# Yellow grains range
lower = np.array([15, 40, 60])
upper = np.array([40, 255, 255])
# Mask grains
mask = cv2.inRange(hsv, lower, upper)
# Morphology cleanup
kernel = np.ones((5, 5), np.uint8)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel, iterations=3)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel, iterations=2)
# Convert mask to binary
ret, thresh = cv2.threshold(mask, 0, 255, cv2.THRESH_BINARY)
# Noise removal
kernel = np.ones((3, 3), np.uint8)
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2)
# Sure background area
sure_bg = cv2.dilate(opening, kernel, iterations=3)
# Sure foreground area
dist_transform = cv2.distanceTransform(opening, cv2.DIST_L2, 5)
ret, sure_fg = cv2.threshold(dist_transform, 0.6 * dist_transform.max(), 255, 0)
# Unknown region
sure_fg = np.uint8(sure_fg)
unknown = cv2.subtract(sure_bg, sure_fg)
# Marker labeling
ret, markers = cv2.connectedComponents(sure_fg)
markers = markers + 1 # background = 1
markers[unknown == 255] = 0
# Apply watershed
markers = cv2.watershed(img, markers)
mask[markers == -1] = 0 # boundaries
return mask, img
def save_grains(mask, img):
# print("Saving grains…")
output_dir = output_folder # Use the folder defined at the top
os.makedirs(output_dir, exist_ok=True)
# Find contours
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
grain_id = 1
for cnt in contours:
x, y, w, h = cv2.boundingRect(cnt)
if w < 10 or h < 10:
continue
grain = img[y:y + h, x:x + w]
filename = os.path.join(output_dir, f"grain_{grain_id}.png")
cv2.imwrite(filename, grain)
print("Saved:", filename)
grain_id += 1
print("nAll grains saved inside folder:", output_dir)
# Draw contours on a copy of the original image
result = img.copy()
cv2.drawContours(result, contours, -1, (0, 0, 255), 2)
# Save the segmented image
segmented_path = os.path.join(output_dir, "segmented_contours.png")
cv2.imwrite(segmented_path, result)
print("Segmented image with contours saved as:", segmented_path)
return result
# ———————————————————
# MAIN EXECUTION
# ———————————————————
if __name__ == "__main__":
# print("Current working directory:", os.getcwd())
mask, img = separate_grains(r"C:UsersDixuDownloadstest1.png")
if mask is not None:
result_img = save_grains(mask, img)
# # Show results
# cv2.namedWindow("Mask", cv2.WINDOW_NORMAL)
# cv2.resizeWindow("Mask", 600, 500)
# cv2.imshow("Mask", mask)
cv2.namedWindow("Segmented Image", cv2.WINDOW_NORMAL)
cv2.resizeWindow("Segmented Image", 600, 500)
cv2.imshow("Segmented Image", result_img)
cv2.waitKey(0)
cv2.destroyAllWindows() import cv2
import numpy as np
import os
output_folder = r"E:grains_output"
# Create the folder if it doesn’t exist
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# Example: saving an image
img = cv2.imread(r"C:UsersDixuDownloadstest1.png") # your grain image
if img is None:
print("Error: Image not found! Check the path and filename.")
exit()
else:
print("Image loaded successfully!")
cv2.imwrite(os.path.join(output_folder, "segmented.png"), img)
# FUNCTION: Separate grains using COLOR segmentation (HSV
def separate_grains(image_path):
print("Loading:", image_path)
img = cv2.imread(image_path)
if img is None:
print("Error: image not found!")
return None, None
# Convert to HSV
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# Yellow grains range
lower = np.array([15, 40, 60])
upper = np.array([40, 255, 255])
# Mask grains
mask = cv2.inRange(hsv, lower, upper)
# Morphology cleanup
kernel = np.ones((5, 5), np.uint8)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel, iterations=3)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel, iterations=2)
# Convert mask to binary
ret, thresh = cv2.threshold(mask, 0, 255, cv2.THRESH_BINARY)
# Noise removal
kernel = np.ones((3, 3), np.uint8)
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2)
# Sure background area
sure_bg = cv2.dilate(opening, kernel, iterations=3)
# Sure foreground area
dist_transform = cv2.distanceTransform(opening, cv2.DIST_L2, 5)
ret, sure_fg = cv2.threshold(dist_transform, 0.6 * dist_transform.max(), 255, 0)
# Unknown region
sure_fg = np.uint8(sure_fg)
unknown = cv2.subtract(sure_bg, sure_fg)
# Marker labeling
ret, markers = cv2.connectedComponents(sure_fg)
markers = markers + 1 # background = 1
markers[unknown == 255] = 0
# Apply watershed
markers = cv2.watershed(img, markers)
mask[markers == -1] = 0 # boundaries
return mask, img
def save_grains(mask, img):
# print("Saving grains…")
output_dir = output_folder # Use the folder defined at the top
os.makedirs(output_dir, exist_ok=True)
# Find contours
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
grain_id = 1
for cnt in contours:
x, y, w, h = cv2.boundingRect(cnt)
if w < 10 or h < 10:
continue
grain = img[y:y + h, x:x + w]
filename = os.path.join(output_dir, f"grain_{grain_id}.png")
cv2.imwrite(filename, grain)
print("Saved:", filename)
grain_id += 1
print("nAll grains saved inside folder:", output_dir)
# Draw contours on a copy of the original image
result = img.copy()
cv2.drawContours(result, contours, -1, (0, 0, 255), 2)
# Save the segmented image
segmented_path = os.path.join(output_dir, "segmented_contours.png")
cv2.imwrite(segmented_path, result)
print("Segmented image with contours saved as:", segmented_path)
return result
# ———————————————————
# MAIN EXECUTION
# ———————————————————
if __name__ == "__main__":
# print("Current working directory:", os.getcwd())
mask, img = separate_grains(r"C:UsersDixuDownloadstest1.png")
if mask is not None:
result_img = save_grains(mask, img)
# # Show results
# cv2.namedWindow("Mask", cv2.WINDOW_NORMAL)
# cv2.resizeWindow("Mask", 600, 500)
# cv2.imshow("Mask", mask)
cv2.namedWindow("Segmented Image", cv2.WINDOW_NORMAL)
cv2.resizeWindow("Segmented Image", 600, 500)
cv2.imshow("Segmented Image", result_img)
cv2.waitKey(0)
cv2.destroyAllWindows() python, cv2, image processing, image segmentation MATLAB Answers — New Questions









