-1

I have to crop image which contains only the part of cv2.HoughCircles() (my code with cv2.HoughCircles() is below)

I want something like this (Cropping circle from image using opencv python) with mask, I tried to do it but I couldn't..

Here is my code:

import cv2
import numpy as np
cam_capture = cv2.VideoCapture(0)
cv2.destroyAllWindows()

while True:
    _, image_frame = cam_capture.read()
    # Rectangle marker
    r = cv2.rectangle(image_frame, upper_left, bottom_right, (0, 0, 255), 3)
    rect_img = image_frame[upper_left[1]: bottom_right[1], upper_left[0]: bottom_right[0]]
    # Replacing the sketched image on Region of Interest
    image_frame[upper_left[1]: bottom_right[1], upper_left[0]: bottom_right[0]] = rect_img
    cv2.imshow("Full window", image_frame)
    #cv2.imshow("ROI", rect_img)
    gray = cv2.cvtColor(rect_img, cv2.COLOR_BGR2GRAY)
    blurred = cv2.medianBlur(gray, 25)
    minDist = 100
    param1 = 30  # 500
    param2 = 50  # 200 #smaller value-> more false circles
    minRadius = 5
    maxRadius = 100  # 10
    circles = cv2.HoughCircles(blurred, 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(rect_img, (i[0], i[1]), i[2], (0, 255, 0), 2)

    cv2.imshow("ROI", rect_img)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cam_capture.release()
cv2.destroyAllWindows()

Please help me!!

Yoyoyo
  • 11
  • 1

1 Answers1

0

You can do that in Python/OpenCV by extracting the center (x,y) and radius (r) of the circle from Hough Circles. Then compute the sides of the crop rectangular ROI from that information.

left = x-r
right = x+r
top = y-r
bottom = y+r

and

crop = input[top:bottom, left:right]
fmw42
  • 46,825
  • 10
  • 62
  • 80
  • Yes but It will cut only square with this circle.. I want only circle with mask around it. – Yoyoyo Feb 23 '21 at 07:00
  • Make a mask by drawing a white filled circle on black background of the same size as your input using the radius and center. Then put the mask into the alpha channel of the input. Then crop as above. (Or crop first and then make a mask similarly the size of the crop). To add the mask to the alpha channel, first convert your image `cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)`. Then `img[:, :, 3] = mask` – fmw42 Feb 23 '21 at 16:26