# Find the center of mass of cells and crop the image

I am trying to make a program to analyze cell nucleus, but in order to do so, I need to isolate each nucleus and crop the image in a way that each nucleus will be centered (its center of mass will be in the middle).

The image looks like this: So far I have created the following code, which puts the squares around the biggest contours found in the image. But that's not really what I wanted...

import cv2
import numpy as np
import tiffcapture as tc

class SelectNucleus(it.ImageTools):
tiff = None
img = None

def __init__(self, path):
self.tiff = tc.opentiff(path)
self.img = np.array(self.img, dtype=np.uint8)

def split_nucleus(self):
"""split image and into few parts, one neclues in each"""
_, thresh = cv2.threshold(self.img, 100, 255, 0)
kernel = np.ones((2, 2), np.uint8)
thresh = cv2.erode(thresh, kernel, iterations=1)
kernel = np.ones((10, 10), np.uint8)
thresh = cv2.dilate(thresh, kernel, iterations=1)

cv2.imshow('a', self.img)
self.img, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

big_contour = []
max = 0
for i in contours:
area = cv2.contourArea(i)  # --- find the contour having biggest area ---
if (area > 5000):
max = area
big_contour.append(i)

self.img = cv2.cvtColor(self.img, cv2.COLOR_GRAY2RGB)

# draw rectangles around contours
for contour in big_contour:
(x, y, w, h) = cv2.boundingRect(contour)
cv2.rectangle(self.img, (x, y), (x + w, y + h), (0, 255, 0), 2)

cv2.drawContours(self.img, big_contour, -1, (255, 0, 0), 3)

cv2.imshow('i', self.img)
cv2.waitKey(0)

a = sn.SelectNucleus('1-4.tif')
a.split_nucleus()


The output looks like this: Do you have any ideas on how to do it?

Thanks

edit retag close merge delete

1

I don't understand really your problem. The center of the bounding boxes approximate quite well the center of gravity of the cells. Otherwise do a connectedComponentsWithStats after the morphology operator to find the real center of gravity for each cell.

1

Sort by » oldest newest most voted

Sorry, maybe I was not precise enough. I need to find the exact center of gravity as you called it, an approximation is not near close enough. Thank you for suggesting connectedComponentsWithStats, I will try it and update my post with the results.

EDIT: I found that the solution is very simple: cv2.moments(c)

more

Official site

GitHub

Wiki

Documentation