0

I am working with binary images in which there are a lot of small blobs. I would like to count the number of blobs and have found out that contours are commonly used to do that. However, the information I get does not allow me to measure certain parameters such as the area and the perimeter of these blobs. Does anybody have any recommendations how to do this with Python?

import cv2
from skimage.measure import regionprops

img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)

image, contours, hierarchy = cv2.findContours(img,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)`
disputator1991
  • 165
  • 5
  • 13
  • `OpenCV` is the usual port-of-call for computer vision problems. – Mark Setchell Apr 04 '18 at 14:25
  • I am already able to count the number of objects using cv2.findContours but I can't use this information to calculate the area and perimeter of each object. – disputator1991 Apr 04 '18 at 14:26
  • Please show your code and identify the problems. – Mark Setchell Apr 04 '18 at 14:27
  • I only have very little code (see above) since I have not found any Python modules that allow me to calculate the area and perimeter of objects within a binary image – disputator1991 Apr 04 '18 at 14:44
  • You can try to find contours in images, to calculate the area you can just fill this contours one by one and then try to measure the white pixels. now as you are doing chain aprrox, just find number of points associated with each contours, it should give you the perimeter. – Saurav Panda Apr 04 '18 at 15:36

1 Answers1

0

Once you have the contours, you can use cv2.contourArea() and cv2.arclength() functions to get area and perimeter respectively. For example, let us say you want to find the area and perimeter of the first contour. The code will be something like this:

contour_area = cv2.contourArea(contours[0])
cont_perimeter = cv2.arcLength(contours[0], True)

You can also use these functions to sort the found contours. For example, to sort your contours based on area,

sorted_contours = sorted(contours, key=cv2.contourArea, reverse=True)

Here, 'reverse=True' sorts and puts it in a descending order -from largest to smallest. Now when you access sorted_contours[0], that is your largest contour found. You can also use other parameters to sort them. Refer here for documentation on some contour features like moments, area, perimeter, etc. that you can extract. Hope this helps!

MK 62665
  • 123
  • 1
  • 8