OpenCV - Detecting circular shapes - python

I have some code which detects circular shapes but I am unable to understand how it works.
From this code:
How can i find the radius and center point of the circle?
What is the behaviour of `cv2.approxPolyDP' for detecting circles?
Now find the contours in the segmented mask
contours, hierarchy = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
Sorting the contours w.r.t contour rect X
contours.sort(key = lambda x:cv2.boundingRect(x)[0])
for contour in contours:
approx = cv2.approxPolyDP(contour, 0.01*cv2.arcLength(contour,True), True)
if len(approx) > 8:
# Find the bounding rect of contour.
contour_bounding_rect = cv2.boundingRect(contour)
mid_point = contour_bounding_rect[0] + contour_bounding_rect[2]/2, contour_bounding_rect[1] + contour_bounding_rect[3]/2
print mid_point[1]/single_element_height, ", ",

So I have figured out the answer to your first question: determining the center and radius of circles in the image.
Initially I am finding all the contours present in the image. Then using a for loop, I found the center and radius using cv2.minEnclosingCircle for every contour in the image. I printed them in the console screen.
contours,hierarchy = cv2.findContours(thresh,2,1)
print len(contours)
cnt = contours
for i in range (len(cnt)):
(x,y),radius = cv2.minEnclosingCircle(cnt[i])
center = (int(x),int(y))
radius = int(radius)
cv2.circle(img,center,radius,(0,255,0),2)
print 'Circle' + str(i) + ': Center =' + str(center) + 'Radius =' + str(radius)
To answer your second question on cv2.approxPolyDP(); this function draws an approximate contour around the object in the image based on a parameter called 'epsilon'. Higher the value of 'epsilon', the contour is roughly approximated. For a lower value of epsilon, the contour grazes almost every edge of the object in the image. Visit THIS PAGE for a better understanding.
Hope this helped!! :)

Don't think approxPolyDP is the right way to go here.
If you have an image where you only have circles and you want to find center and radius, try minEnclosingCircle()
If you have an image where you have various shapes and you want to find the circles, try Hough transform (may take a long time) or fitEllipse() where you check if the bounding box it returns is square.
See documentation for both these functions

Related

python opencv - filter contours by position

I use this code to find some blobs, and pick the biggest one.
contours, hierarchy = cv2.findContours(th1, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
if len(contours) != 0:
c = max(contours, key=cv2.contourArea)
Now, I would need to change this code in a way so it returns the contour that is in the middle of the frame. (its bounding box covers the center pixel of the image)
I am not able to figure out how to do this except getting the bounding box of all contours with
xbox, ybox, wbox, hbox = cv2.boundingRect(cont)
and then checking that x and y are smaller than the centere, and x+w and y+h aare bigger than the centre. It does not look like a efficient way tough, since there can be up to 500 small controus..
There is a function in OpenCV that will check if a given point is inside a contour (returns a 1), on the boundary (returns a 0) or outside (returns a -1).
cv2.pointPolygonTest()
I'd like to suggest this approach, maybe there is a more straightforward one. I'm writing code here, but instead giving a possible algorithm:
Iterate over contours and draw each single contour using a mask in a binary mat (b/w and filled)
Check if the center pixel (image width/2, image height/2) is equal to 1
That should work.

Extract most central area in a Binary Image

I am processing binary images, and was previously using this code to find the largest area in the binary image:
# Use the hue value to convert to binary
thresh = 20
thresh, thresh_img = cv2.threshold(h, thresh, 255, cv2.THRESH_BINARY)
cv2.imshow('thresh', thresh_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# Finding Contours
# Use a copy of the image since findContours alters the image
contours, _ = cv2.findContours(thresh_img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
#Extract the largest area
c = max(contours, key=cv2.contourArea)
This code isn't really doing what I need it to do, now I think it would better to extract the most central area in the binary image.
Binary Image
Largest Image
This is currently what the code is extracting, but I am hoping to get the central circle in the first binary image extracted.
OpenCV comes with a point-polygon test function (for contours). It even gives a signed distance, if you ask for that.
I'll find the contour that is closest to the center of the picture. That may be a contour actually overlapping the center of the picture.
Timings, on my quadcore from 2012, give or take a millisecond:
findContours: ~1 millisecond
all pointPolygonTests and argmax: ~1 millisecond
mask = cv.imread("fkljm.png", cv.IMREAD_GRAYSCALE)
(height, width) = mask.shape
ret, mask = cv.threshold(mask, 128, 255, cv.THRESH_BINARY) # required because the sample picture isn't exactly clean
# get contours
contours, hierarchy = cv.findContours(mask, cv.RETR_LIST | cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
center = (np.array([width, height]) - 1) / 2
# find contour closest to center of picture
distances = [
cv.pointPolygonTest(contour, center, True) # looking for most positive (inside); negative is outside
for contour in contours
]
iclosest = np.argmax(distances)
print("closest contour is", iclosest, "with distance", distances[iclosest])
# draw closest contour
canvas = cv.cvtColor(mask, cv.COLOR_GRAY2BGR)
cv.drawContours(image=canvas, contours=[contours[iclosest]], contourIdx=-1, color=(0, 255, 0), thickness=5)
closest contour is 45 with distance 65.19202405202648
a cv.floodFill() on the center point can also quickly yield a labeling on that blob... assuming the mask is positive there. Otherwise, there needs to be search.
(cx, cy) = center.astype(int)
assert mask[cy,cx], "floodFill not applicable"
# trying cv.floodFill on the image center
mask2 = mask >> 1 # turns everything else gray
cv.floodFill(image=mask2, mask=None, seedPoint=center.astype(int), newVal=255)
# use (mask2 == 255) to identify that blob
This also takes less than a millisecond.
Some practically faster approaches might involve a pyramid scheme (low-res versions of the mask) to quickly identify areas of the picture that are candidates for an exact test (distance/intersection).
Test target pixel. Hit (positive)? Done.
Calculate low-res mask. Per block, if any pixel is positive, block is positive.
Find positive blocks, sort by distance, examine closer all those that are within sqrt(2) * blocksize of the best distance.
There are several ways you define "most central." I chose to define it as the region with the closest distance to the point you're searching for. If the point is inside the region, then that distance will be zero.
I also chose to do this with a pixel-based approach rather than a polygon-based approach, like you're doing with findContours().
Here's a step-by-step breakdown of what this code is doing.
Load the image, put it into grayscale, and threshold it. You're already doing these things.
Identify connected components of the image. Connected components are places where there are white pixels which are directly connected to other white pixels. This breaks up the image into regions.
Using np.argwhere(), convert a true/false mask into an array of coordinates.
For each coordinate, compute the Euclidean distance between that point and search_point.
Find the minimum within each region.
Across all regions, find the smallest distance.
import cv2
import numpy as np
img = cv2.imread('test197_img.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, thresh_img = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
n_groups, comp_grouped = cv2.connectedComponents(thresh_img)
components = []
search_point = [600, 150]
for i in range(1, n_groups):
mask = (comp_grouped == i)
component_coords = np.argwhere(mask)[:, ::-1]
min_distance = np.sqrt(((component_coords - search_point) ** 2).sum(axis=1)).min()
components.append({
'mask': mask,
'min_distance': min_distance,
})
closest = min(components, key=lambda x: x['min_distance'])['mask']
Output:

Deskewing MNIST dataset images using minAreaRect() of opencv

I used opencv's minAreaRect to deskew the mnist digits.It worked well for most of the digits but,in some cases the minAreaRect was not detected correctly and it lead to further skewing of the digits.
Images with which this code worked:
Input image:
minAreaRect Image:
deskewed image:
But,for this the didn't work well:
Input image:
minAreaRect Image:
deskewed image:
I want to mention here that I did use: #coords = np.column_stack(np.where(thresh>0)) but,this didn't work at all.
Please suggest a solution using minAreaRect(Preferred) function of opencv.
And I've tested with several images and I do understand that the problem is with the formation of the min Area Rectangle,in the second example it is clear that the min Area rectangle is not visible(because it passess through the digit itself).
Here goes the code:
import numpy as np
import cv2
image=cv2.imread('MNIST/mnist_png/testing/9/73.png')#for 4##5032,6780 #8527,2436,1391
gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)## for 9 problem with 4665,8998,73,7
gray=cv2.bitwise_not(gray)
Gblur=cv2.blur(gray,(5,5))
thresh=cv2.threshold(Gblur,0,255,cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
#cv2.imshow("gray_thresh_blur",thresh)
#Finding Contours will be used to draw the min area rectangle
_,contours,_=cv2.findContours(thresh.copy(),cv2.RETR_LIST,cv2.CHAIN_APPROX_NONE)
cnt1 = contours[0]
cnt=cv2.convexHull(contours[0])
angle = cv2.minAreaRect(cnt)[-1]
print("Actual angle is:"+str(angle))
rect = cv2.minAreaRect(cnt)
p=np.array(rect[1])
#print(p[0])
if p[0] < p[1]:
print("Angle along the longer side:"+str(rect[-1] + 180))
act_angle=rect[-1]+180
else:
print("Angle along the longer side:"+str(rect[-1] + 90))
act_angle=rect[-1]+90
#act_angle gives the angle with bounding box
if act_angle < 90:
angle = (90 + angle)
print("angleless than -45")
# otherwise, just take the inverse of the angle to make
# it positive
else:
angle=act_angle-180
print("grter than 90")
# rotate the image to deskew it
(h, w) = image.shape[:2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated = cv2.warpAffine(image,M,(w,h),flags=cv2.INTER_CUBIC,borderMode=cv2.BORDER_REPLICATE)
box = cv2.boxPoints(rect)
print(box)
box = np.int0(box)
print(box)
p=cv2.drawContours(thresh,[box],0,(0,0,255),1)
print("contours"+str(p))
cv2.imwrite("post/MinAreaRect9.png",p)
cv2.imwrite("post/Input_9.png", image)
cv2.imwrite('post/Deskewed_9.png', rotated)
A few points to take note of:
Most of OpenCV's functions work with white foreground and black background. So comment out this line:
gray=cv2.bitwise_not(gray)
Make sure you're computing the EXTERNEL contours of the letters. This means that you need to ignore all the child contours. For this use cv2.RETR_EXTERNAL.
contours=cv2.findContours(thresh.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[1]
Finally make sure you're assigning the correct angle to find rotation matrix.
With these changes:

How to close contour over outline rather than edge - OpenCV

Tl;DR: How to measure area enclosed by contour rather than just the contour line itself
I want to find the outline of the object in the below image and have a code that works for most cases.
Thresholding and adpative thresholding do not work reliably as the ligthing changes. I use a Canny edge detection and check the area to ensure I found the proper contour. However, once in a while, when there is a gap that cannot be closed by morphological closing, the shape is correct but the area is of the contour line instead of the whole object.
What I usually do is use convexHull, as it returns a contour around the object. However, in this case the object curves inwards along the top and convexHull isn't a good approximation to the area anymore.
I tried using approxPolyDP but the area that gets returned is of the contour line rather than the object.
How can I get the approxPolyDP to return a similar closed contour around the object, just like the convexHull function does?
Code illustrating this using the above picture:
import cv2
img = cv2.imread('Img_0.jpg',0)
cv2.imshow('Original', img)
edges = cv2.Canny(img,50,150)
cv2.imshow('Canny', edges)
contours, hierarchy = cv2.findContours(edges,cv2.cv.CV_RETR_EXTERNAL,cv2.cv.CV_CHAIN_APPROX_NONE)
cnt = contours[1] #I have a function to do this but for simplicity here by hand
M = cv2.moments(cnt)
print('Area = %f \t' %M['m00'], end="")
cntHull = cv2.convexHull(cnt, returnPoints=True)
cntPoly=cv2.approxPolyDP(cnt, epsilon=1, closed=True)
MHull = cv2.moments(cntHull)
MPoly = cv2.moments(cntPoly)
print('Area after Convec Hull = %f \t Area after apporxPoly = %f \n' %(MHull['m00'], MPoly['m00']), end="")
x, y =img.shape
size = (w, h, channels) = (x, y, 1)
canvas = np.zeros(size, np.uint8)
cv2.drawContours(canvas, cnt, -1, 255)
cv2.imshow('Contour', canvas)
canvas = np.zeros(size, np.uint8)
cv2.drawContours(canvas, cntHull, -1, 255)
cv2.imshow('Hull', canvas)
canvas = np.zeros(size, np.uint8)
cv2.drawContours(canvas, cntPoly, -1, 255)
cv2.imshow('Poly', canvas)
The output from the code is
Area = 24.500000 Area after Convec Hull = 3960.500000 Area after apporxPoly = 29.500000
Here's a very promising ppt from geosensor.net that discusses several algorithms. My recommendation would be to use the swing arm method with a limited radius.
Another completely un-tested, off the wall idea I have is to scan across the image by row and column (more directions increase accuracy) and color in the regions between line intersections:
_______
/-------\
/---------\
--------+---------+------ (fill between 2 intersections)
| |
|
--------+---------------- (no fill between single intersection)
\
-------
the maximum error would then decrease as the number of line directions scanned increases (more than 90 and 45 degrees). Getting a final area would then be as simple as a pixel count.

OpenCV2 in Python throwing error with inRange

So I looked pretty hard, but I couldn't find much of anything on OpenCV errors, and definitely no documentation discussing possible errors and their causes. I'm using OpenCV2 with Python 2.7, trying to track colored puff balls live with a webcam. To do this, I get the center of a colored ball by thresholding the latest image from the webcam around the HSV values that the puff ball appears as. Unfortunately, this doesn't always seem to work, and throws a very mysterious error:
cv2.error: .../matrix.cpp:235: error: (-215) step[dims-1] == (size_t)CV_ELEM_SIZE(flags) in function create
I have no idea why it would be throwing this. The code that spawns it is:
def getColorCenter(self, imgHSV, lowerBound, upperBound, debugName = None):
detectedImg = cv2.inRange(imgHSV, lowerBound, upperBound)
if str(lowerBound) == str(self.GREEN_LOWER_BOUND):
cv2.imshow(str(lowerBound) + "puffball", detectedImg)
center = self.getCenterOfLargestBlob(detectedImg, debugName)
return center
and in particular the line detectedImg = cv2.inRange(imgHSV, lowerBound, upperBound).
Any idea what might solve this issue?
The error might be caused if the webcam doesn't detect any blobs.
A better approach to your problem would be to use contours.
You can go over all the contours in your image and select the one with largest area. Then you can return the centroid of the largest contour.
detectedImg = cv2.inRange(imgHSV, lowerBound, upperBound)
# If there is a lot of noise in your image it would help to open and dilate
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))
detectedImg_open = cv2.morphologyEx(detectedImg, cv2.MORPH_OPEN, kernel)
detectedImg_dilate = cv2.dilate(detectedImg_open, kernel, iterations = 1)
Now find the contours :
_, contours, _ = cv2.findContours(detectedImg_dilate, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
Find the largest contour by area:
largest_contour_val = 0
largest_contour_pos = 0
for i in xrange(len(contours)):
if cv2.contourArea(contours[i])>largest_contour_val:
largest_contour_val = cv2.contourArea(contours[i])
largest_contour_pos = i
Now only if there exists at least one contour, we return the centroid of the largest contour:
if len(contours)!=0:
# find centroid and return it
M = cv2.moments(contours[largest_contour_pos])
x = int(M['m10']/M['m00'])
y = int(M['m01']/M['m00'])
center = (x,y)
return center

Categories

Resources