def render_lane(image, corners, ploty, fitx, ):
_, src, dst = perspective_transform(image, corners)
Minv = cv2.getPerspectiveTransform(dst, src)
# Create an image to draw the lines on
warp_zero = np.zeros_like(image[:,:,0]).astype(np.uint8)
color_warp = np.dstack((warp_zero, warp_zero, warp_zero))
# Recast the x and y points into usable format for cv2.fillPoly()
pts = np.vstack((fitx,ploty)).astype(np.int32).T
# Draw the lane onto the warped blank image
#plt.plot(left_fitx, ploty, color='yellow')
cv2.polylines(color_warp, [pts], False, (0, 255, 0), 10)
#cv2.fillPoly(color_warp, np.int_([pts]), (0, 255, 0))
# Warp the blank back to original image space using inverse perspective matrix (Minv)
newwarp = cv2.warpPerspective(color_warp, Minv, (image.shape[1], image.shape[0]))
# Combine the result with the original image
result = cv2.addWeighted(image, 1, newwarp, 0.3, 0)
return result
python类fillPoly()的实例源码
def roi(img,vertices):
# blank mask:
mask = np.zeros_like(img)
# filling pixels inside the polygon defined by "vertices" with the fill color
cv2.fillPoly(mask, vertices, 255)
# returning the image only where mask pixels are nonzero
masked = cv2.bitwise_and(img, mask)
return masked
def draw_landmarks(frame, lds):
#cv2.rectangle(frame, (0, 0), (frame.shape[1], frame.shape[0]), (0, 0, 0), -1)
# Make the eyebrows into a nightmare
cv2.fillPoly(frame, [lds.get('left_eyebrow')], (68, 54, 39, 128))
cv2.fillPoly(frame, [lds.get('right_eyebrow')], (68, 54, 39, 128))
cv2.fillPoly(frame, [lds.get('left_eye')], (150, 54, 39, 128))
cv2.fillPoly(frame, [lds.get('right_eye')], (150, 54, 39, 128))
# Gloss the lips
cv2.fillPoly(frame, [lds.get('top_lip')], (150, 0, 0, 128))
cv2.fillPoly(frame, [lds.get('bottom_lip')], (150, 0, 0, 128))
cv2.fillPoly(frame, [lds.get('nose_bridge')], (150, 0, 0, 128))
cv2.fillPoly(frame, [lds.get('nose_tip')], (150, 0, 0, 128))
cv2.polylines(frame, [lds.get('chin')], False, (150, 0, 0, 128))
def findEllipses(edges):
contours, _ = cv2.findContours(edges.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
ellipseMask = np.zeros(edges.shape, dtype=np.uint8)
contourMask = np.zeros(edges.shape, dtype=np.uint8)
pi_4 = np.pi * 4
for i, contour in enumerate(contours):
if len(contour) < 5:
continue
area = cv2.contourArea(contour)
if area <= 100: # skip ellipses smaller then 10x10
continue
arclen = cv2.arcLength(contour, True)
circularity = (pi_4 * area) / (arclen * arclen)
ellipse = cv2.fitEllipse(contour)
poly = cv2.ellipse2Poly((int(ellipse[0][0]), int(ellipse[0][1])), (int(ellipse[1][0] / 2), int(ellipse[1][1] / 2)), int(ellipse[2]), 0, 360, 5)
# if contour is circular enough
if circularity > 0.6:
cv2.fillPoly(ellipseMask, [poly], 255)
continue
# if contour has enough similarity to an ellipse
similarity = cv2.matchShapes(poly.reshape((poly.shape[0], 1, poly.shape[1])), contour, cv2.cv.CV_CONTOURS_MATCH_I2, 0)
if similarity <= 0.2:
cv2.fillPoly(contourMask, [poly], 255)
return ellipseMask, contourMask
def _get_mask(self, scan, slide, series):
img, s, o, origShape = scan
mask = np.zeros((origShape[1], origShape[2]))
nodules = self._nodule_info[series]
for nodule in nodules:
iid, z, edges = nodule
z = int((z - o[2])/s[2])
if z == slide:
if edges.shape[0] > 1:
cv.fillPoly(mask, [edges], 255)
else:
#It's a small nodule. Make a circle of radius 3mm
edges = np.squeeze(edges)
center = tuple(edges)
radius = max(3.0/s[0], 3.0/s[1])
cv.circle(mask, center, int(radius+1), 255, -1)
if img.shape[1] != origShape[1] or img.shape[2] != origShape[2]:
mask = imu.resize_2d(mask, (img.shape[1], img.shape[2]))
return mask
def region_of_interest(img, vertices):
"""
Applies an image mask.
Only keeps the region of the image defined by the polygon
formed from `vertices`. The rest of the image is set to black.
"""
# defining a blank mask to start with
mask = np.zeros_like(img)
# defining a 3 channel or 1 channel color to fill the mask with depending on the input image
if len(img.shape) > 2:
channel_count = img.shape[2] # i.e. 3 or 4 depending on your image
ignore_mask_color = (255,) * channel_count
else:
ignore_mask_color = 255
# filling pixels inside the polygon defined by "vertices" with the fill color
cv2.fillPoly(mask, vertices, ignore_mask_color)
# returning the image only where mask pixels are nonzero
masked_image = cv2.bitwise_and(img, mask)
return masked_image
def process_one(image_dir, page_dir, output_dir, basename, colormap, color_labels):
image_filename = os.path.join(image_dir, "{}.jpg".format(basename))
page_filename = os.path.join(page_dir, "{}.xml".format(basename))
page = PAGE.parse_file(page_filename)
text_lines = [tl for tr in page.text_regions for tl in tr.text_lines]
graphic_regions = page.graphic_regions
img = imread(image_filename, mode='RGB')
gt = np.zeros_like(img[:, :, 0])
mask1 = cv2.fillPoly(gt.copy(), [PAGE.Point.list_to_cv2poly(tl.coords)
for tl in text_lines if 'comment' in tl.id], 1)
mask2 = cv2.fillPoly(gt.copy(), [PAGE.Point.list_to_cv2poly(tl.coords)
for tl in text_lines if not 'comment' in tl.id], 1)
mask3 = cv2.fillPoly(gt.copy(), [PAGE.Point.list_to_cv2poly(tl.coords)
for tl in graphic_regions], 1)
arr = np.dstack([mask1, mask2, mask3])
gt_img = convert_array_masks(arr, colormap, color_labels)
save_and_resize(img, os.path.join(output_dir, 'images', '{}.jpg'.format(basename)))
save_and_resize(gt_img, os.path.join(output_dir, 'labels', '{}.png'.format(basename)), nearest=True)
def findSignificantContours(img, sobel_8u, sobel):
image, contours, heirarchy = cv2.findContours(sobel_8u, \
cv2.RETR_EXTERNAL, \
cv2.CHAIN_APPROX_SIMPLE)
mask = np.ones(image.shape[:2], dtype="uint8") * 255
level1 = []
for i, tupl in enumerate(heirarchy[0]):
if tupl[3] == -1:
tupl = np.insert(tupl, 0, [i])
level1.append(tupl)
significant = []
tooSmall = sobel_8u.size * 10 / 100
for tupl in level1:
contour = contours[tupl[0]];
area = cv2.contourArea(contour)
if area > tooSmall:
cv2.drawContours(mask, \
[contour], 0, (0, 255, 0), \
2, cv2.LINE_AA, maxLevel=1)
significant.append([contour, area])
significant.sort(key=lambda x: x[1])
significant = [x[0] for x in significant];
peri = cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, 0.02 * peri, True)
mask = sobel.copy()
mask[mask > 0] = 0
cv2.fillPoly(mask, significant, 255, 0)
mask = np.logical_not(mask)
img[mask] = 0;
return img
def mask(self, size = (151, 151)):
"""Returns a binary mask for the worm shape
Arguments:
size (tuple ro array): size of the mask
Returns:
array: mask of worm shape
"""
mask = np.zeros(tuple(size));
xyl, xyr, xym = self.sides();
for i in range(self.npoints-1):
poly = np.array([xyl[i,:], xyr[i,:], xyr[i+1,:], xyl[i+1,:]], dtype = np.int32)
cv2.fillPoly(mask, [poly], 1);
return np.asarray(mask, dtype = bool)
def mask(self, size = (151, 151)):
"""Returns a binary mask for the worm shape
Arguments:
size (tuple ro array): size of the mask
Returns:
array: mask of worm shape
"""
mask = np.zeros(tuple(size));
left, right = self.shape();
for i in range(self.npoints-1):
poly = np.array([left[i,:], right[i,:], right[i+1,:], left[i+1,:]], dtype = np.int32)
cv2.fillPoly(mask, [poly], 1);
return np.asarray(mask, dtype = bool)
def mask(self, size = (151, 151)):
"""Returns a binary mask for the worm shape
Arguments:
size (tuple ro array): size of the mask
Returns:
array: mask of worm shape
"""
mask = np.zeros(tuple(size));
left, right = self.shape();
for i in range(self.npoints-1):
poly = np.array([left[i,:], right[i,:], right[i+1,:], left[i+1,:]], dtype = np.int32)
cv2.fillPoly(mask, [poly], 1);
return np.asarray(mask, dtype = bool)
def mask(self, size = (151, 151)):
"""Returns a binary mask for the worm shape
Arguments:
size (tuple ro array): size of the mask
Returns:
array: mask of worm shape
"""
mask = np.zeros(tuple(size));
left, right = self.shape();
for i in range(self.npoints-1):
poly = np.array([left[i,:], right[i,:], right[i+1,:], left[i+1,:]], dtype = np.int32)
cv2.fillPoly(mask, [poly], 1);
return np.asarray(mask, dtype = bool)
def region_of_interest(img, vertices):
"""
Applies an image mask.
Only keeps the region of the image defined by the polygon
formed from `vertices`. The rest of the image is set to black.
"""
#defining a blank mask to start with
mask = np.zeros_like(img)
#defining a 3 channel or 1 channel color to fill the mask with depending on the input image
if len(img.shape) > 2:
channel_count = img.shape[2] # i.e. 3 or 4 depending on your image
ignore_mask_color = (255,) * channel_count
else:
ignore_mask_color = 255
#filling pixels inside the polygon defined by "vertices" with the fill color
cv2.fillPoly(mask, vertices, ignore_mask_color)
#returning the image only where mask pixels are nonzero
masked_image = cv2.bitwise_and(img, mask)
return masked_image
def load_contour(contour, img_path):
filename = "IM-%s-%04d.dcm" % (SAX_SERIES[contour.case], contour.img_no)
full_path = os.path.join(img_path, contour.case, filename)
f = dicom.read_file(full_path)
ctrs = np.loadtxt(contour.ctr_path, delimiter=" ").astype(np.int)
label = np.zeros(f.pixel_array.shape, dtype=np.uint8)
cv2.fillPoly(label, [ctrs], 255)
img,lab = getAlignImg(f,label);
lx,ly = img.shape;
assert(lx==ly);
xm,ym = np.where(lab>127);
if xm.size<30:
xm,ym = lx//2,ly//2;
xm = np.mean(xm);
ym = np.mean(ym);
delta = int(lx*0.62)//2;#cut middle 160x160 from 256x256 for sunny brook data
assert(delta<xm and delta<ym);
xm,ym,delta = int(xm),int(ym),int(delta);
img = img[xm-delta:xm+delta,ym-delta:ym+delta];
lab = lab[xm-delta:xm+delta,ym-delta:ym+delta];
return cv2.resize(img, (SZ,SZ)), cv2.resize(lab, (SZ,SZ))
def contour_mask(self, contour):
""" Generates a binary image with only the given contour filled in. """
# fill in new data
new_data = np.zeros(self.data.shape)
num_boundary = contour.boundary_pixels.shape[0]
boundary_px_ij_swapped = np.zeros([num_boundary, 1, 2])
boundary_px_ij_swapped[:, 0, 0] = contour.boundary_pixels[:, 1]
boundary_px_ij_swapped[:, 0, 1] = contour.boundary_pixels[:, 0]
cv2.fillPoly(
new_data, pts=[
boundary_px_ij_swapped.astype(
np.int32)], color=(
BINARY_IM_MAX_VAL, BINARY_IM_MAX_VAL, BINARY_IM_MAX_VAL))
orig_zeros = np.where(self.data == 0)
new_data[orig_zeros[0], orig_zeros[1]] = 0
return BinaryImage(new_data.astype(np.uint8), frame=self._frame)
project3.py 文件源码
项目:Self-Driving-Car-ND-Predict-Steering-Angle-with-CV
作者: sjamthe
项目源码
文件源码
阅读 27
收藏 0
点赞 0
评论 0
def region_of_interest(img, vertices):
"""
Applies an image mask.
Only keeps the region of the image defined by the polygon
formed from `vertices`. The rest of the image is set to black.
"""
#defining a blank mask to start with
mask = np.zeros_like(img)
#defining a 3 channel or 1 channel color to fill the mask with depending on the input image
if len(img.shape) > 2:
channel_count = img.shape[2] # i.e. 3 or 4 depending on your image
ignore_mask_color = (255,) * channel_count
else:
ignore_mask_color = 255
#filling pixels inside the polygon defined by "vertices" with the fill color
cv2.fillPoly(mask, vertices, ignore_mask_color)
#returning the image only where mask pixels are nonzero
masked_image = cv2.bitwise_and(img, mask)
return masked_image
baseline_generate_dataset.py 文件源码
项目:DocumentSegmentation
作者: SeguinBe
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
def process_one(image_filename, output_dir, basename):
page = PAGE.parse_file(get_page_filename(image_filename))
text_lines = [tl for tr in page.text_regions for tl in tr.text_lines]
img = imread(image_filename, mode='RGB')
gt = np.zeros_like(img)
cv2.fillPoly(gt, [PAGE.Point.list_to_cv2poly(tl.coords) for tl in text_lines], DRAWING_COLOR)
save_and_resize(img, os.path.join(output_dir, 'images', '{}.jpg'.format(basename)))
save_and_resize(gt, os.path.join(output_dir, 'labels', '{}.png'.format(basename)), nearest=True)
classes = np.stack([(0, 0, 0), DRAWING_COLOR])
np.savetxt(os.path.join(output_dir, 'classes.txt'), classes, fmt='%d')
Preprocessing.py 文件源码
项目:Dstl-Satellite-Imagery-Feature-Detection
作者: DeepVoltaire
项目源码
文件源码
阅读 27
收藏 0
点赞 0
评论 0
def _plot_mask_from_contours(raster_img_size, contours, class_value=1):
"""
Creates a class mask (0 and 1s) from lists of exterior and interior polygon coordinates.
"""
img_mask = np.zeros(raster_img_size, np.uint8)
if contours is None:
return img_mask
perim_list, interior_list = contours
cv2.fillPoly(img_mask, perim_list, class_value)
cv2.fillPoly(img_mask, interior_list, 0)
return img_mask
def region_of_interest(img, vertices):
"""
Applies an image mask.
Only keeps the region of the image defined by the polygon
formed from `vertices`. The rest of the image is set to black.
"""
# defining a blank mask to start with
mask = np.zeros_like(img)
# defining a 3 channel or 1 channel color to fill the mask with depending on the input image
if len(img.shape) > 2:
channel_count = img.shape[2] # i.e. 3 or 4 depending on your image
ignore_mask_color = (255,) * channel_count
else:
ignore_mask_color = 255
# filling pixels inside the polygon defined by "vertices" with the fill color
cv2.fillPoly(mask, vertices, ignore_mask_color)
# returning the image only where mask pixels are nonzero
masked_image = cv2.bitwise_and(img, mask)
return masked_image
def visualize(hog, grid=(10, 10), radCircle=None):
'''
visualize HOG as polynomial around cell center
for [grid] * cells
'''
s0, s1, nang = hog.shape
angles = np.linspace(0, np.pi, nang + 1)[:-1]
# center of each sub array:
cx, cy = s0 // (2 * grid[0]), s1 // (2 * grid[1])
# max. radius of polynomial around cenetr:
rx, ry = cx, cy
# for drawing a position indicator (circle):
if radCircle is None:
radCircle = max(1, rx // 10)
# output array:
out = np.zeros((s0, s1), dtype=np.uint8)
# point of polynomial:
pts = np.empty(shape=(1, 2 * nang, 2), dtype=np.int32)
# takes grid[0]*grid[1] sample HOG values:
samplesHOG = subCell2DFnArray(hog, lambda arr: arr[cx, cy], grid)
mxHOG = samplesHOG.max()
# sub array slices:
slices = list(subCell2DSlices(out, grid))
m = 0
for m, hhh in enumerate(samplesHOG.reshape(grid[0] * grid[1], nang)):
hhmax = hhh.max()
hh = hhh / hhmax
sout = out[slices[m][2:4]]
for n, (o, a) in enumerate(zip(hh, angles)):
pts[0, n, 0] = cx + np.cos(a) * o * rx
pts[0, n, 1] = cy + np.sin(a) * o * ry
pts[0, n + nang, 0] = cx + np.cos(a + np.pi) * o * rx
pts[0, n + nang, 1] = cy + np.sin(a + np.pi) * o * ry
cv2.fillPoly(sout, pts, int(255 * hhmax / mxHOG))
cv2.circle(sout, (cx, cy), radCircle, 0, thickness=-1)
return out
def _createMaskFromSelection(self):
img = self.display.widget.image
assert img is not None, 'need image defined'
out = np.zeros(img.shape[1:3], dtype=np.uint8)
for n, p in enumerate(self.paths):
assert isinstance(
p, FreehandItem), 'TODO: make work for other items as well'
cv2.fillPoly(out, np.array([p.elements()], dtype=np.int32), n + 1)
self.handleOutput([out.T], title='selection')
def mask_for_polygons(
im_size: Tuple[int, int], polygons: MultiPolygon) -> np.ndarray:
""" Return numpy mask for given polygons.
polygons should already be converted to image coordinates.
"""
img_mask = np.zeros(im_size, np.uint8)
if not polygons:
return img_mask
int_coords = lambda x: np.array(x).round().astype(np.int32)
exteriors = [int_coords(poly.exterior.coords) for poly in polygons]
interiors = [int_coords(pi.coords) for poly in polygons
for pi in poly.interiors]
cv2.fillPoly(img_mask, exteriors, 1)
cv2.fillPoly(img_mask, interiors, 0)
return img_mask
def get_mask_polygons(polygons, height, width):
"""Turn a list of polygons into a mask image of height by width.
Each polygon is expressed as a list of [x, y] points."""
mask = np.zeros((height, width), dtype=np.ubyte)
cv2.fillPoly(mask, np.int32(polygons), color=255)
return mask
def load_contour(contour, img_path):
filename = 'IM-%s-%04d.dcm' % (sax_series_dict[contour.case], contour.img_no)
full_path = os.path.join(img_path, contour.case, filename)
f = dicom.read_file(full_path)
img = f.pixel_array.astype(np.uint8)
ctrs = np.loadtxt(contour.ctr_path, delimiter=' ').astype(np.int)
label = np.zeros_like(img, dtype='uint8')
cv2.fillPoly(label, [ctrs], 1)
return cv2.resize(img, (img_size,img_size)), cv2.resize(label, (img_size,img_size))
masks.py 文件源码
项目:kaggle-dstl-satellite-imagery-feature-detection
作者: alno
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
def plot_contours(raster_size, contours, class_value=1):
# __author__ = visoft
# https://www.kaggle.com/visoft/dstl-satellite-imagery-feature-detection/export-pixel-wise-mask
img_mask = np.zeros(raster_size, np.uint8)
if contours is None:
return img_mask
perim_list, interior_list = contours
cv2.fillPoly(img_mask, perim_list, class_value)
cv2.fillPoly(img_mask, interior_list, 0)
return img_mask
def apply(self, item, pth):
item.id += f'-{self.id}'
img = item.img_mat
mask = np.zeros(img.shape, np.uint8)
channel_count = img.shape[2]
ignore_mask_color = (255,) * channel_count
cv2.fillPoly(mask, [pth], ignore_mask_color)
item.img_mat = cv2.bitwise_and(img, mask)
yield item
def roi_mask(img, vertices):
mask = np.zeros_like(img)
# defining a 3 channel or 1 channel color to fill the mask with depending on the input image
if len(img.shape) > 2:
channel_count = img.shape[2] # i.e. 3 or 4 depending on your image
mask_color = (255,) * channel_count
else:
mask_color = 255
cv2.fillPoly(mask, vertices, mask_color)
masked_img = cv2.bitwise_and(img, mask)
return masked_img
def houghTransformAndRegionSelect(image, edges):
rho = 1
theta = np.pi/180
threshold = 1
min_line_length = 5
max_line_gap = 3
# Next we'll create a masked edges image using cv2.fillPoly()
mask = np.zeros_like(edges)
ignore_mask_color = 255
# This time we are defining a four sided polygon to mask
imshape = image.shape
vertices = np.array([[(0,imshape[0]),(450, 290), (490, 290), (imshape[1],imshape[0])]], dtype=np.int32)
cv2.fillPoly(mask, vertices, ignore_mask_color)
masked_edges = cv2.bitwise_and(edges, mask)
line_image = np.copy(image)*0
# Run Hough on edge detected image
# Output "lines" is an array containing endpoints of detected line segments
lines = cv2.HoughLinesP(masked_edges, rho, theta, threshold, np.array([]), min_line_length, max_line_gap)
# Iterate over the output "lines" and draw lines on a blank image
for line in lines:
for x1,y1,x2,y2 in line:
cv2.line(line_image,(x1,y1),(x2,y2),(255,0,0),10)
# Create a "color" binary image to combine with line image
color_edges = np.dstack((edges, edges, edges))
# Draw the lines on the edge image
lines_edges = cv2.addWeighted(color_edges, 0.8, line_image, 1, 0)
return lines_edges
def roi(img, vertices):
mask = np.zeros_like(img)
cv2.fillPoly(mask, vertices, 255)
masked = cv2.bitwise_and(img, mask)
return masked
def roi(img, vertices):
#blank mask:
mask = np.zeros_like(img)
#filling pixels inside the polygon defined by "vertices" with the fill color
cv2.fillPoly(mask, vertices, 255)
#returning the image only where mask pixels are nonzero
masked = cv2.bitwise_and(img, mask)
return masked