Abi sb
Abi sb

Reputation: 189

opencv and python how croped circle area only

I want to circle shape crop using only a point to the center. What is the easiest way of doing this?Thanks my code

import numpy as np
import cv2

img = cv2.imread('lenna.png',cv2.IMREAD_COLOR)
cv2.circle(img,(312,237), 63, (0,0,0),2)
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Upvotes: 4

Views: 3926

Answers (2)

noone
noone

Reputation: 6558

Here you can crop the circle from this script

import cv2
import numpy as np
img = cv2.imread('test2.jpg', cv2.IMREAD_COLOR)
x=256
y=256
r=63
# crop image as a square
img = img[y:y+r*2, x:x+r*2]
# create a mask
mask = np.full((img.shape[0], img.shape[1]), 0, dtype=np.uint8) 
# create circle mask, center, radius, fill color, size of the border
cv2.circle(mask,(r,r), r, (255,255,255),-1)
# get only the inside pixels
fg = cv2.bitwise_or(img, img, mask=mask)

mask = cv2.bitwise_not(mask)
background = np.full(img.shape, 255, dtype=np.uint8)
bk = cv2.bitwise_or(background, background, mask=mask)
final = cv2.bitwise_or(fg, bk)
cv2.imshow('image',final)
cv2.waitKey(0)
cv2.destroyAllWindows()

Upvotes: 4

Ishara Dayarathna
Ishara Dayarathna

Reputation: 3601

Here is the solution:

Suppose center of the circle is (a1,b1) and radius is r. Then cropping coordinates would be [ a1-r:a1+r , b1-r:b1+r ].

import numpy as np
import cv2

img = cv2.imread('lenna.png',cv2.IMREAD_COLOR)
a1=256
b1=256
r=63
cv2.circle(img,(a1,b1), r, (0,0,0),2)
result = img[a1-r:a1+r,b1-r:b1+r]
cv2.imshow('image',img)
cv2.imshow('result',result)
cv2.waitKey(0)
cv2.destroyAllWindows()

Upvotes: -1

Related Questions