def circle(self, row: int, col: int, radius: float,
color: ColorType, fill: bool=False, alpha=1.0) -> 'Layer':
"""
Draw a circle centered on the specified row and column,
with the given radius.
:param row: Center row of circle
:param col: Center column of circle
:param radius: Radius of circle
:param color: Color to draw with
:param fill: True if the circle should be filled
:return: This frame instance
"""
if fill:
rr, cc = draw.circle(row, col, round(radius), shape=self.matrix.shape)
self._draw(rr, cc, color, alpha)
else:
rr, cc, aa = draw.circle_perimeter_aa(row, col, round(radius), shape=self.matrix.shape)
self._draw(rr, cc, color, aa)
return self
python类circle()的实例源码
def get_img_mask(scan, h, nodules, nth=-1, z=None):
"""
h = spacing_z/spacing_xy
nodules = list (x,y,z,r) of the nodule, in Voxel space
specify nth or z. nth: the nth nodule
"""
if z is None:
z = int(nodules[nth][2]);
img = normalize(scan[z,:,:]);
res = np.zeros(img.shape);
#draw nodules
for xyzd in nodules:
r = xyzd[3]/2.0;
dz = np.abs((xyzd[2]-z)*h);
if dz>=r:continue
rlayer = np.sqrt(r**2-dz**2);
if rlayer<3:continue
#create contour at xyzd[0],xyzd[1] with radius rlayer
rr,cc=draw.circle(xyzd[1],xyzd[0],rlayer)
res[rr,cc] = 1;
return img,res;
def create_polygon_mask( image, xcorners, ycorners ):
'''
Give image and x/y coners to create a polygon mask
image: 2d array
xcorners, list, points of x coners
ycorners, list, points of y coners
Return:
the polygon mask: 2d array, the polygon pixels with values 1 and others with 0
Example:
'''
from skimage.draw import line_aa, line, polygon, circle
imy, imx = image.shape
bst_mask = np.zeros_like( image , dtype = bool)
rr, cc = polygon( ycorners,xcorners)
bst_mask[rr,cc] =1
#full_mask= ~bst_mask
return bst_mask
def create_rectangle_mask( image, xcorners, ycorners ):
'''
Give image and x/y coners to create a rectangle mask
image: 2d array
xcorners, list, points of x coners
ycorners, list, points of y coners
Return:
the polygon mask: 2d array, the polygon pixels with values 1 and others with 0
Example:
'''
from skimage.draw import line_aa, line, polygon, circle
imy, imx = image.shape
bst_mask = np.zeros_like( image , dtype = bool)
rr, cc = polygon( ycorners,xcorners)
bst_mask[rr,cc] =1
#full_mask= ~bst_mask
return bst_mask
def process_failure(name):
name = name.replace("mask","truth")
name2 = name.replace("truth","")
image,_,_ = image_read_write.load_itk_image(name2)
#image_cropped = image[:,120:420,60:460]
image_mask = np.zeros(image.shape)
center = 256
cc,rr = circle(center+20,center,160)
image_mask[:,cc,rr] = 1
image[image>threshold]=0
image[image!=0]=1
image = image*image_mask
#image_cropped[image_cropped>threshold]=0
#image_cropped[image_cropped!=0]=1
kernel20 = np.zeros((15,15))
cc,rr = circle(7,7,8)
kernel20[cc,rr]=1
image = binary_closing(image, [kernel20],1)
#image[:,:,:]=0
#image[:,120:420,60:460]=image_cropped
truth,_,_ = image_read_write.load_itk_image(name)
print evaluator.calculate_dice(image,truth,name)
image = np.array(image,dtype=np.int8)
#LoadImages.save_itk(image,name)
def process_failure(name):
name = name.replace("mask","truth")
name2 = name.replace("truth","")
image,_,_ = image_read_write.load_itk_image(name2)
#image_cropped = image[:,120:420,60:460]
image_mask = np.zeros(image.shape)
center = 256
cc,rr = circle(center+20,center,160)
image_mask[:,cc,rr] = 1
image[image>threshold]=0
image[image!=0]=1
image = image*image_mask
#image_cropped[image_cropped>threshold]=0
#image_cropped[image_cropped!=0]=1
kernel20 = np.zeros((15,15))
cc,rr = circle(7,7,8)
kernel20[cc,rr]=1
image = binary_closing(image, [kernel20],1)
#image[:,:,:]=0
#image[:,120:420,60:460]=image_cropped
truth,_,_ = image_read_write.load_itk_image(name)
print evaluator.calculate_dice(image,truth,name)
image = np.array(image,dtype=np.int8)
#LoadImages.save_itk(image,name)
def ellipse(self, row: int, col: int, radius_r: float, radius_c: float,
color: ColorType, fill: bool=False, alpha: float=1.0) -> 'Layer':
"""
Draw an ellipse centered on the specified row and column,
with the given radiuses.
:param row: Center row of ellipse
:param col: Center column of ellipse
:param radius_r: Radius of ellipse on y axis
:param radius_c: Radius of ellipse on x axis
:param color: Color to draw with
:param fill: True if the circle should be filled
:return: This frame instance
"""
if fill:
rr, cc = draw.ellipse(row, col, math.floor(radius_r), math.floor(radius_c),
shape=self.matrix.shape)
self._draw(rr, cc, color, alpha)
else:
rr, cc = draw.ellipse_perimeter(row, col, math.floor(radius_r), math.floor(radius_c),
shape=self.matrix.shape)
self._draw(rr, cc, color, alpha)
return self
def set_circular_observation(self, img, col_center, row_center, radius, color=(0,0,0)):
rr,cc = circle(row_center, col_center, radius)
# make sure within bounds of img
rr[rr<0] = 0
rr[rr>img.shape[0]-1] = img.shape[0]-1
cc[cc<0] = 0
cc[cc>img.shape[1]-1] = img.shape[1]-1
img[rr,cc] = color
return img
def mask_grid(pos, grid, radius, one_is_free=True):
"""Mask a grid.
Parameters
----------
pos : tuple
the center of the circle (row, col)
e.g. (2,3) = center at 3rd row, 4th column
grid : numpy.ndarray
should be a 2d matrix
e.g. 8x8, 16x16, 28x28, 40x40
imsize : tuple
the grid size
radius : int
the length of the radius
one_is_free : bool
if True, then 1 is freezone, 0 is block
if False, then 0 is freezone, 1 is block
Returns
-------
masked_grid : numpy.ndarray
the masked grid
"""
mask = np.zeros_like(grid)
new_grid = grid.copy()
rr, cc = draw.circle(pos[0], pos[1], radius=radius,
shape=mask.shape)
mask[rr, cc] = 1
if one_is_free:
return new_grid*mask, (rr, cc)
else:
masked_img = np.ones_like(new_grid)
masked_img[rr, cc] = new_grid[rr, cc]
return masked_img
def create_wedge( image, center, radius, wcors, acute_angle=True) :
'''YG develop at June 18, 2017, @CHX
Create a wedge by a combination of circle and a triangle defined by center and wcors
wcors: [ [x1,x2,x3...], [y1,y2,y3..]
'''
from skimage.draw import line_aa, line, polygon, circle
imy, imx = image.shape
cy,cx = center
x = [cx] + list(wcors[0])
y = [cy] + list(wcors[1])
maskc = np.zeros_like( image , dtype = bool)
rr, cc = circle( cy, cx, radius, shape = image.shape)
maskc[rr,cc] =1
maskp = np.zeros_like( image , dtype = bool)
x = np.array( x )
y = np.array( y )
print(x,y)
rr, cc = polygon( y,x)
maskp[rr,cc] =1
if acute_angle:
return maskc*maskp
else:
return maskc*~maskp
def annotation2pltpatch(annotation, **kwargs):
"""
Convert geometric annotation to matplotlib geometric objects (=patches)
For details regarding matplotlib patches see:
http://matplotlib.org/api/patches_api.html
For annotation formats see:
imageutil.annotation2coords
:param annotation annotation: Annotation of an image region such as
point, circle, rect or polyline
:return: matplotlib.patches
:rtype: generator over matplotlib patches
"""
if not annotation or isnan(annotation):
return
kind, geometries = annotation
for geo in geometries:
if kind == 'point':
pltpatch = plp.CirclePolygon((geo[0], geo[1]), 1, **kwargs)
elif kind == 'circle':
pltpatch = plp.Circle((geo[0], geo[1]), geo[2], **kwargs)
elif kind == 'rect':
x, y, w, h = geo
pltpatch = plp.Rectangle((x, y), w, h, **kwargs)
elif kind == 'polyline':
pltpatch = plp.Polygon(geo, closed=False, **kwargs)
else:
raise ValueError('Invalid kind of annotation: ' + kind)
yield pltpatch
def annotation2mask(image, annotations, pos=255):
"""
Convert geometric annotation to mask.
For annotation formats see:
imageutil.annotation2coords
>>> import numpy as np
>>> img = np.zeros((3, 3), dtype='uint8')
>>> anno = ('point', ((0, 1), (2, 0)))
>>> annotation2mask(img, anno)
array([[ 0, 0, 255],
[255, 0, 0],
[ 0, 0, 0]], dtype=uint8)
:param annotation annotation: Annotation of an image region such as
point, circle, rect or polyline
:param int pos: Value to write in mask for regions defined by annotation
:param numpy array image: Image annotation refers to.
Returned mask will be of same size.
:return: Mask with annotation
:rtype: numpy array
"""
mask = np.zeros(image.shape[:2], dtype=np.uint8)
for rr, cc in annotation2coords(image, annotations):
mask[rr, cc] = pos
return mask
def DiskKernel(dim):
kernelwidth = dim
kernel = np.zeros((kernelwidth, kernelwidth), dtype=np.float32)
circleCenterCoord = dim / 2
circleRadius = circleCenterCoord +1
rr, cc = circle(circleCenterCoord, circleCenterCoord, circleRadius)
kernel[rr,cc]=1
if(dim == 3 or dim == 5):
kernel = Adjust(kernel, dim)
normalizationFactor = np.count_nonzero(kernel)
kernel = kernel / normalizationFactor
return kernel
def circle_mask_blurred( img, radius, sig = 20 ):
'''Creates a blurred circle, using supplied image as template for dimensions'''
height, width, ch = img.shape
centre_y = (height-1) / 2.
centre_x = (width-1) / 2.
img_copy = img.copy()
img_copy[:, :, :] = (0.,0.,0.)
rr, cc = draw.circle(centre_y, centre_x, radius, img.shape)
img_copy[rr, cc, :] = (1.,1.,1.)
img_copy = filters.gaussian(img_copy, sigma=sig, mode='nearest', multichannel=True)
return img_copy
def generate_image(width, height):
image = np.zeros([height, width], dtype=np.float32)
count = np.random.randint(min_count, max_count+1)
half_size = dot_size/2
for i in range(count):
x = np.random.randint(half_size, width - half_size)
y = np.random.randint(half_size, height - half_size)
rr, cc = circle(x, y, half_size)
image[rr, cc] = 1.0
return image, count
def create_cross_mask( image, center, wy_left=4, wy_right=4, wx_up=4, wx_down=4,
center_circle = True, center_radius=10
):
'''
Give image and the beam center to create a cross-shaped mask
wy_left: the width of left h-line
wy_right: the width of rigth h-line
wx_up: the width of up v-line
wx_down: the width of down v-line
center_circle: if True, create a circle with center and center_radius
Return:
the cross mask
'''
from skimage.draw import line_aa, line, polygon, circle
imy, imx = image.shape
cx,cy = center
bst_mask = np.zeros_like( image , dtype = bool)
###
#for right part
wy = wy_right
x = np.array( [ cx, imx, imx, cx ])
y = np.array( [ cy-wy, cy-wy, cy + wy, cy + wy])
rr, cc = polygon( y,x)
bst_mask[rr,cc] =1
###
#for left part
wy = wy_left
x = np.array( [0, cx, cx,0 ])
y = np.array( [ cy-wy, cy-wy, cy + wy, cy + wy])
rr, cc = polygon( y,x)
bst_mask[rr,cc] =1
###
#for up part
wx = wx_up
x = np.array( [ cx-wx, cx + wx, cx+wx, cx-wx ])
y = np.array( [ cy, cy, imy, imy])
rr, cc = polygon( y,x)
bst_mask[rr,cc] =1
###
#for low part
wx = wx_down
x = np.array( [ cx-wx, cx + wx, cx+wx, cx-wx ])
y = np.array( [ 0,0, cy, cy])
rr, cc = polygon( y,x)
bst_mask[rr,cc] =1
if center_radius!=0:
rr, cc = circle( cy, cx, center_radius, shape = bst_mask.shape)
bst_mask[rr,cc] =1
full_mask= ~bst_mask
return full_mask