I am working on a project involving thousands of images containing irregular-shaped adjacent cells. While I have extensive experience with Python, my image-processing expertise is limited. My objectives for this project are as follows:
- Cell Identification: Detect and identify all individual cells within each image.
- Cell Labeling: Assign a specific code or unique identifier to each detected cell and annotate the cell with this identifier at its center. Additionally, calculate and display the surface area of each cell.
- Edge Cell Detection: Ignore cells located at the edges of the images that are incomplete or partially visible.
import cv2
import numpy as np
# Load the image
image = cv2.imread('cells.tif')
# Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Apply thresholding
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# Find contours
contours, _ = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# Iterate through contours to identify shapes and calculate their areas
shapeCount=0
for contour in contours:
# Approximate the contour to a simpler shape
epsilon = 0.04 * cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, epsilon, True)
# Calculate the area
area = cv2.contourArea(contour)
# Draw the contour and label the shape on the original image
cv2.drawContours(image, [contour], -1, (0, 255, 0), 2)
cv2.putText(image, f"{shapeCount} -- {int(area)}", (contour[0][0][0] - 10, contour[0][0][1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)
shapeCount +=1
# Display the image with shapes identified
cv2.imshow('Shapes', image)
cv2.waitKey(0)
cv2.destroyAllWindows()