I'm trying to detect this black circle here. Shouldn't be too difficult but for some reason I just get 0 circles or approximately 500 circles everywhere, depending on the arguments. But there is no middle ground. Feels like I have tried to play with the arguments for hours, but absolutely no success. Is there a problem using HoughCircles and black or white picture? The task seems simple to a human eye, but is this difficult to the computer for some reason?
Here's my code:
import numpy as np
import cv2
image = cv2.imread('temp.png')
output = image.copy()
blurred = cv2.blur(image,(10,10))
gray = cv2.cvtColor(blurred, cv2.COLOR_BGR2GRAY)
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1.5, 20, 100, 600, 10, 100)
if circles is not None:
circles = np.round(circles[0, :]).astype("int")
print len(circles)
for (x, y, r) in circles:
cv2.circle(output, (x, y), r, (0, 255, 0), 4)
cv2.rectangle(output, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)
show the output image
cv2.imshow("output", np.hstack([output]))
cv2.waitKey(0)
There are few minor mistakes in your approach.
Here is the code I used from the documentation:
img = cv2.imread('temp.png',0)
img = cv2.medianBlur(img,5)
cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)
cimg1 = cimg.copy()
circles = cv2.HoughCircles img,cv2.HOUGH_GRADIENT,1,20,param1=50,param2=30,minRadius=0,maxRadius=0)
circles = np.uint16(np.around(circles))
for i in circles[0,:]:
# draw the outer circle
cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)
# draw the center of the circle
cv2.circle(cimg,(i[0],i[1]),2,(0,255,255),3)
cv2.imshow('detected circles.jpg',cimg)
joint = np.hstack([cimg1, cimg]) #---Posting the original image along with the image having the detected circle
cv2.imshow('detected circle and output', joint )
Related
I'm using OpenCV houghcircles to identify all the circles (both hollow and filled). Follow is my code:
import numpy as np
import cv2
img = cv2.imread('images/32x32.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
bilateral = cv2.bilateralFilter(gray,10,50,50)
minDist = 30
param1 = 30
param2 = 50
minRadius = 5
maxRadius = 100
circles = cv2.HoughCircles(bilateral, cv2.HOUGH_GRADIENT, 1, minDist, param1=param1, param2=param2, minRadius=minRadius, maxRadius=maxRadius)
if circles is not None:
circles = np.uint16(np.around(circles))
for i in circles[0,:]:
cv2.circle(img, (i[0], i[1]), i[2], (0, 0, 255), 2)
# Show result for testing:
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Test input image 1:
Test output image1:
As you can see I'm able identity most of the circles except for few. What am I missing here? I've tried varying the parameters but this is the best i could get.
Also, if I use even more compact circles the script does not identify any circles whatsoever.
An alternative idea is to use find contour method and chek whether the contour is a circle using appox as below.
import cv2
img = cv2.imread('32x32.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
inputImageCopy = img.copy()
# Find the circle blobs on the binary mask:
contours, hierarchy = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Use a list to store the center and radius of the target circles:
detectedCircles = []
# Look for the outer contours:
for i, c in enumerate(contours):
# Approximate the contour to a circle:
(x, y), radius = cv2.minEnclosingCircle(c)
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.02 * peri, True)
if len(approx)>5: # check if the contour is circle
# Compute the center and radius:
center = (int(x), int(y))
radius = int(radius)
# Draw the circles:
cv2.circle(inputImageCopy, center, radius, (0, 0, 255), 2)
# Store the center and radius:
detectedCircles.append([center, radius])
cv2.imshow("Circles", inputImageCopy)
cv2.waitKey(0)
cv2.destroyAllWindows()
I solved your problem. Using same code as your. No needed to modified. I changed value from 50 to 30. That all.
#!/usr/bin/python39
#OpenCV 4.5.5 Raspberry Pi 3/B/4B-w/4/8GB RAM, Bullseye,v11.
#Date: 19th April, 2022
import numpy as np
import cv2
img = cv2.imread('fill_circles.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
bilateral = cv2.bilateralFilter(gray,10,50,50)
minDist = 30
param1 = 30
param2 = 30
minRadius = 5
maxRadius = 100
circles = cv2.HoughCircles(bilateral, cv2.HOUGH_GRADIENT, 1, minDist, param1=param1, param2=param2, minRadius=minRadius, maxRadius=maxRadius)
if circles is not None:
circles = np.uint16(np.around(circles))
for i in circles[0,:]:
cv2.circle(img, (i[0], i[1]), i[2], (0, 0, 255), 2)
cv2.imwrite('lego.png', img)
# Show result for testing:
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Output:
If you can always get(or create from real image) such "clean" image, the bounding-box of the grid(2-dimensional array of circles) region can be easily obtained.
Therefore, you can know the rectangular area of interest (and the angle of rotation of the grid, if rotation is possible).
If you examine the pixels along the axial direction of the rectangle, you can easily find out how many circles are lined up and the diameter of the circle.
Because lines that all pixel are black are gaps between adjacent row(or column).
(Sum up the pixel values along the direction of the axis. Whether it is 0 or not tells you whether the line passes over the grid-cell or not.)
If necessary, you may check that the shape of the contour in each gird-cell is really circular.
import numpy as np
import cv2
import matplotlib.pyplot as plt
import copy
image = cv2.imread('C:/Users/Deepak Padhi/Desktop/download.png')
#cv2.imshow('Filtered_original',image)
image = cv2.GaussianBlur(image,(5,5),0)
orig_image = np.copy(image)
gray= image[:,:,1]
output=gray.copy()
##cv2.imshow("gray", gray)
##cv2.waitKey(0)
circles=cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 3, 4.0)
circles = np.uint16(np.around(circles))
for i in circles[0,:]:
# draw the outer circle
cv2.circle(output,(i[0],i[1]),i[2],(0,255,0),2)
# draw the center of the circle
cv2.circle(output,(i[0],i[1]),2,(0,0,255),3)
cv2.imshow('detected circles',output)
This is the code I used to try and detect all circles in the given image:
Image of circles
Which parameter and how should I manipulate to detect the smaller as well as the larger circles? I had tried minRadius and maxRadius to possible values as per both circles, but it didn't work, so I let it reset to default.
It feels like the canny edge detector is actually detecting the smaller circles with the default arguments(100,100), as attached canny detection
I took the Green plane of the given image:Original Image
I would recommend you to first read the docs.
If you just change the param1 and param2 which are thresholds for the Canny edge detector, the cv2.HoughCircles works fine.
Here the code:
import cv2
import numpy as np
image = cv2.imread('circles.png')
image = cv2.GaussianBlur(image, (5, 5), 0)
orig_image = np.copy(image)
gray = image[:, :, 1]
output = gray.copy()
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=20,
minRadius=0, maxRadius=0)
circles = np.uint16(np.around(circles))
for i in circles[0,:]:
# draw the outer circle
cv2.circle(output, (i[0], i[1]), i[2], (0, 255, 0), 2)
# draw the center of the circle
cv2.circle(output, (i[0], i[1]), 2, (0, 0, 255), 3)
cv2.imwrite('detected circles.png', output)
So I have this image (480, 640, 3):
And I want to do detect different circles in it (mainly the red one, but you don't care).
Here is my code :
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread('img0.png')
print(img.shape)
sat = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)[:, :, 1]
print(img.shape)
circles = circles = cv2.HoughCircles(sat, cv2.HOUGH_GRADIENT, 1, minDist=30, maxRadius=500)
print(circles)
if circles is not None: # code stolen from here : https://www.pyimagesearch.com/2014/07/21/detecting-circles-images-using-opencv-hough-circles/
# convert the (x, y) coordinates and radius of the circles to integers
circles = np.round(circles[0, :]).astype("int")
# loop over the (x, y) coordinates and radius of the circles
for (x, y, r) in circles:
# draw the circle in the output image, then draw a rectangle
# corresponding to the center of the circle
cv2.circle(img, (x, y), r, (0, 255, 0), 4)
cv2.rectangle(img, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)
plt.imshow(img)
plt.show()
Note that I use the saturation for the gray image, as I want the red part of my hand spinner, it is easier for me
Which output this :
Which is not that bad for me(ignore the wrong color scheme, It's bgr of opencv displayed as rgb), except that there is circles with too big radius. The output of print(circle) is :
[[[420.5 182.5 141.3]
[420.5 238.5 84.5]
[335.5 283.5 35. ]
[253.5 323.5 42.7]
[417.5 337.5 43.6]]]
(it is [x,y, radius])
Basically, it means that circles of interest has radius below 50, and I want to get rid of the two first one. I wanted to use the maxRadius parameter (notice that in my code, it is currently 500). So my guess was that if I set maxRadius at 50, it would remove the unwanted radius, but instead, it deleted all the circles... I have found that with maxRadius at 400, I got an output that "works":
And with maxRadius below 200, there is no more circles found.
What I am missing here ?
I am working on windows, python 3.7.7, last version of opencv
The following seems to work in Python/OpenCV.
Read the input
Convert to HSV and extract the saturation channel
Median filter
Do Hough Circles processing
Draw the circles
Save the results
Input
import cv2
import numpy as np
# Read image
img = cv2.imread('circles.png')
hh, ww = img.shape[:2]
# Convert to HSV and extract the saturation channel
sat = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)[:,:,1]
# median filter
median = cv2.medianBlur(sat, 7)
# get Hough circles
min_dist = int(ww/20)
circles = cv2.HoughCircles(median, cv2.HOUGH_GRADIENT, 1, minDist=min_dist, param1=150, param2=50, minRadius=0, maxRadius=0)
print(circles)
# draw circles
result = img.copy()
for circle in circles[0]:
# draw the circle in the output image, then draw a rectangle
# corresponding to the center of the circle
(x,y,r) = circle
x = int(x)
y = int(y)
cv2.circle(result, (x, y), r, (0, 255, 0), 4)
cv2.rectangle(result, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)
# save results
cv2.imwrite('circles_saturation.jpg', sat)
cv2.imwrite('circles_median.jpg', sat)
cv2.imwrite('circles_result.jpg', result)
# show images
cv2.imshow('sat', sat)
cv2.imshow('median', median)
cv2.imshow('result', result)
cv2.waitKey(0)
cv2.destroyAllWindows()
Saturation image:
Median filtered image:
Results:
Circles data:
[[[258.5 323.5 52.7]
[340.5 193.5 51.3]
[422.5 326.5 34.1]
[333.5 276.5 33.6]]]
I try to recognize two areas in the following image. The area inside the inner and the area between the outer and inner - the border - circle with python openCV.
I tried different approaches like:
Detecting circles images using opencv hough circles
Find and draw contours using opencv python
That does not fit very well.
Is this even possible with classical image processing or do I need some neuronal networking?
Edit: Detecting circles images using opencv hough circles
# import the necessary packages
import numpy as np
import argparse
import cv2
from PIL import Image
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required = True, help = "Path to the image")
args = vars(ap.parse_args())
# load the image, clone it for output, and then convert it to grayscale
image = cv2.imread(args["image"])
output = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# detect circles in the image
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1.2, 500)
# ensure at least some circles were found
if circles is not None:
# convert the (x, y) coordinates and radius of the circles to integers
circles = np.round(circles[0, :]).astype("int")
# loop over the (x, y) coordinates and radius of the circles
for (x, y, r) in circles:
# draw the circle in the output image, then draw a rectangle
# corresponding to the center of the circle
cv2.circle(output, (x, y), r, (0, 255, 0), 4)
cv2.rectangle(output, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)
# show the output image
img = Image.fromarray(image)
if img.height > 1500:
imS = cv2.resize(np.hstack([image, output]), (round((img.width * 2) / 3), round(img.height / 3)))
else:
imS = np.hstack([image, output])
# Resize image
cv2.imshow("gray", gray)
cv2.imshow("output", imS)
cv2.waitKey(0)
else:
print("No circle detected")
Testimage:
General mistake: While using HoughCircles() , the parameters should be chosen appropriately. I see that you are only using first 4 parameters in your code. Ypu can check here to get a good idea about those parameters.
Experienced idea: While using HoughCircles , I noticed that if 2 centers of 2 circles are same or almost close to each other, HoughCircles cant detect them. Even if you assign min_dist parameter to a small value. In your case, the center of circles also same.
My suggestion: I will attach the appropriate parameters with the code for both circles. I couldnt find 2 circles with one parameter list because of the problem I explained above. My suggestion is that apply these two parameters double time for the same image and just get the circles and get the result.
For outer circle result and parameters included code:
Result:
# import the necessary packages
import numpy as np
import argparse
import cv2
from PIL import Image
# load the image, clone it for output, and then convert it to grayscale
image = cv2.imread('image.jpg')
output = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.medianBlur(gray,15)
rows = gray.shape[0]
# detect circles in the image
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT,1, rows / 8,
param1=100, param2=30,
minRadius=200, maxRadius=260)
# ensure at least some circles were found
if circles is not None:
# convert the (x, y) coordinates and radius of the circles to integers
circles = np.round(circles[0, :]).astype("int")
# loop over the (x, y) coordinates and radius of the circles
for (x, y, r) in circles:
# draw the circle in the output image, then draw a rectangle
# corresponding to the center of the circle
cv2.circle(output, (x, y), r, (0, 255, 0), 4)
cv2.rectangle(output, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)
# show the output image
img = Image.fromarray(image)
if img.height > 1500:
imS = cv2.resize(np.hstack([image, output]), (round((img.width * 2) / 3), round(img.height / 3)))
else:
imS = np.hstack([image, output])
# Resize image
cv2.imshow("gray", gray)
cv2.imshow("output", imS)
cv2.waitKey(0)
else:
print("No circle detected")
For inner circle the parameters:
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT,1, rows / 8,
param1=100, param2=30,
minRadius=100, maxRadius=200)
Result:
I have an Image in which i want to extract a region of interest which is a circle
and then crop it.
I have done some preprocessing and i am sharing the result and code.
please let me know how can i achieve this.
import imutils
import cv2
import numpy as np
#edge detection
image = cv2.imread('newimage.jpg')
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
image = cv2.GaussianBlur(image, (5, 5), 0)
canny = cv2.Canny(image, 30, 150)
#circle detection
img = cv2.medianBlur(image,5)
cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)
circles = cv2.HoughCircles(canny,cv2.HOUGH_GRADIENT,1,20,
param1=50,param2=30,minRadius=0,maxRadius=0)
circles = np.uint16(np.around(circles))
for i in circles[0,:]:
#outer circle
cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)
#center of the circle
cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)
plt.title('Circle Detected')
plt.xticks([])
plt.yticks([])
plt.imshow(cimg,cmap = 'gray')
plt.show()
In your example you should get circle with the biggest radius which is in i[2]
max_circle = max(circles[0,:], key=lambda x:x[2])
print(max_circle)
i = max_circle
#outer circle
cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)
#center of the circle
cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)
Check this out, the main tips:
play with blurring params;
play with HoughCircles params: minSize, maxSize and minDist
(minimal distance between circles)
img = cv2.imread('newimage.jpg', cv2.IMREAD_COLOR)
# Convert to grayscale and blur
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray_blurred = cv2.bilateralFilter(gray, 11, 30, 30)
# tune circles size
detected_circles = cv2.HoughCircles(gray_blurred,
cv2.HOUGH_GRADIENT, 1,
param1=50,
param2=30,
minDist=100,
minRadius=50,
maxRadius=70)
if detected_circles is not None:
# Convert the circle parameters a, b and r to integers.
detected_circles = np.uint16(np.around(detected_circles))
for pt in detected_circles[0, :]:
a, b, r = pt[0], pt[1], pt[2]
# Draw the circumference of the circle.
cv2.circle(img, (a, b), r, (0, 255, 0), 2)
# Draw a small circle (of radius 1) to show the center.
cv2.circle(img, (a, b), 1, (0, 0, 255), 3)
cv2.imshow("Detected circles", img)
cv2.waitKey(0)
small circle values:
minRadius=50
maxRadius=60
big circle values:
minRadius=100
maxRadius=200