def img_fill(im_in, n): # n = binary image threshold
th, im_th = cv2.threshold(im_in, n, 255, cv2.THRESH_BINARY);
# Copy the thresholded image.
im_floodfill = im_th.copy()
# Mask used to flood filling.
# Notice the size needs to be 2 pixels than the image.
h, w = im_th.shape[:2]
mask = np.zeros((h + 2, w + 2), np.uint8)
# Floodfill from point (0, 0)
cv2.floodFill(im_floodfill, mask, (0, 0), 255);
# Invert floodfilled image
im_floodfill_inv = cv2.bitwise_not(im_floodfill)
# Combine the two images to get the foreground.
fill_image = im_th | im_floodfill_inv
return fill_image
python类floodFill()的实例源码
def threshold_and_label_blobs(intensity, blob_list, threshold):
# we cheat a little here because we take the list of
# known blob locations to fill the thresholded areas
# surrounding the blob centers. This way false blob detections
# are avoided.
assert(intensity.dtype == np.uint8)
W, H = intensity.shape
_, blobs_mask = cv2.threshold(intensity, threshold, 1, cv2.THRESH_BINARY)
labels = 255 - blobs_mask
for num, pk in enumerate(blob_list):
iy, ix = int(pk.y), int(pk.x)
if labels[ix, iy] < 254: # was the area under the blob location already filled by another blob?
return None # overlapping non-separable blobs
if labels[ix, iy] == 255:
return None # blob center is not in thresholded area
cv2.floodFill(labels.reshape((W, H, 1)), None, (iy, ix), (num,), (0,), (0,))
labels[labels == 254] = 255 # everything not a proper blob is assigned label 255
return labels
def select_largest_obj(self, img_bin, lab_val=255, fill_holes=False,
smooth_boundary=False, kernel_size=15):
'''Select the largest object from a binary image and optionally
fill holes inside it and smooth its boundary.
Args:
img_bin (2D array): 2D numpy array of binary image.
lab_val ([int]): integer value used for the label of the largest
object. Default is 255.
fill_holes ([boolean]): whether fill the holes inside the largest
object or not. Default is false.
smooth_boundary ([boolean]): whether smooth the boundary of the
largest object using morphological opening or not. Default
is false.
kernel_size ([int]): the size of the kernel used for morphological
operation. Default is 15.
Returns:
a binary image as a mask for the largest object.
'''
n_labels, img_labeled, lab_stats, _ = \
cv2.connectedComponentsWithStats(img_bin, connectivity=8,
ltype=cv2.CV_32S)
largest_obj_lab = np.argmax(lab_stats[1:, 4]) + 1
largest_mask = np.zeros(img_bin.shape, dtype=np.uint8)
largest_mask[img_labeled == largest_obj_lab] = lab_val
# import pdb; pdb.set_trace()
if fill_holes:
bkg_locs = np.where(img_labeled == 0)
bkg_seed = (bkg_locs[0][0], bkg_locs[1][0])
img_floodfill = largest_mask.copy()
h_, w_ = largest_mask.shape
mask_ = np.zeros((h_ + 2, w_ + 2), dtype=np.uint8)
cv2.floodFill(img_floodfill, mask_, seedPoint=bkg_seed,
newVal=lab_val)
holes_mask = cv2.bitwise_not(img_floodfill) # mask of the holes.
largest_mask = largest_mask + holes_mask
if smooth_boundary:
kernel_ = np.ones((kernel_size, kernel_size), dtype=np.uint8)
largest_mask = cv2.morphologyEx(largest_mask, cv2.MORPH_OPEN,
kernel_)
return largest_mask
def img_fill(im_in,n): # n = binary image threshold
th, im_th = cv2.threshold(im_in, n, 255, cv2.THRESH_BINARY);
# Copy the thresholded image.
im_floodfill = im_th.copy()
# Mask used to flood filling.
# Notice the size needs to be 2 pixels than the image.
h, w = im_th.shape[:2]
mask = np.zeros((h+2, w+2), np.uint8)
# Floodfill from point (0, 0)
cv2.floodFill(im_floodfill, mask, (0,0), 255);
# Invert floodfilled image
im_floodfill_inv = cv2.bitwise_not(im_floodfill)
# Combine the two images to get the foreground.
fill_image = im_th | im_floodfill_inv
return fill_image
def activate_boolean_map(bool_map):
"""
Performs activation on a single boolean map.
"""
# use the boolean map as a mask for flood filling
activation = np.array(bool_map, dtype=np.uint8)
mask_shape = (bool_map.shape[0] + 2, bool_map.shape[1] + 2)
ffill_mask = np.zeros(mask_shape, dtype=np.uint8)
# top and bottom rows
for i in range(0, activation.shape[0]):
for j in [0, activation.shape[1] - 1]:
if activation[i,j]:
cv2.floodFill(activation, ffill_mask, (j, i), 0)
# left and right columns
for i in [0, activation.shape[0] - 1]:
for j in range(0, activation.shape[1]):
if activation[i,j]:
cv2.floodFill(activation, ffill_mask, (j, i), 0)
return activation
RRTstar_Scan1.py 文件源码
项目:Rapidly-Exploring-Random-Tree-Star-Scan
作者: vampcoder
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def markVisibleArea(self, originalImg):
visibleImg = np.zeros(self.img.shape, np.uint8)
x, y = self.current[0], self.current[1]
lx, ly = -200, -200 #last coordinates
points = []
for i in range(1083):
nx, ny = self.findNearestObstacle(originalImg, x, y, i/3)
#print nx, ny
nx = int(nx)
ny = int(ny)
points.append((ny, nx))
if i != 0:
cv2.line(visibleImg, (ny, nx), (ly, lx), 100, 1)
lx, ly = nx, ny
h, w = visibleImg.shape
mask = np.zeros((h+2, w+2), np.uint8)
cv2.floodFill(visibleImg, mask, (y, x), 100)
for i in points:
cv2.circle(visibleImg, i, 3, 255, 6)
self.img = cv2.bitwise_or(self.img, visibleImg)
RRT_Scan_final.py 文件源码
项目:Rapidly-Exploring-Random-Tree-Star-Scan
作者: vampcoder
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def markVisibleArea(self, originalImg):
visibleImg = np.zeros(self.img.shape, np.uint8)
x, y = self.current[0], self.current[1]
lx, ly = -200, -200 #last coordinates
points = []
for i in range(1083):
nx, ny = self.findNearestObstacle(originalImg, x, y, i/3)
#print nx, ny
nx = int(nx)
ny = int(ny)
points.append((ny, nx))
if i != 0:
cv2.line(visibleImg, (ny, nx), (ly, lx), 100, 1)
lx, ly = nx, ny
h, w = visibleImg.shape
mask = np.zeros((h+2, w+2), np.uint8)
cv2.floodFill(visibleImg, mask, (y, x), 100)
for i in points:
cv2.circle(visibleImg, i, 3, 255, 6)
self.img = cv2.bitwise_or(self.img, visibleImg)
def cropCircle(img, resize=None):
if resize:
if (img.shape[0] > img.shape[1]):
tile_size = (int(img.shape[1] * resize / img.shape[0]), resize)
else:
tile_size = (resize, int(img.shape[0] * resize / img.shape[1]))
img = cv2.resize(img, dsize=tile_size, interpolation=cv2.INTER_CUBIC)
else:
tile_size = img.shape
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY);
_, thresh = cv2.threshold(gray, 10, 255, cv2.THRESH_BINARY)
_, contours, _ = cv2.findContours(thresh.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
main_contour = sorted(contours, key=cv2.contourArea, reverse=True)[0]
ff = np.zeros((gray.shape[0], gray.shape[1]), 'uint8')
cv2.drawContours(ff, main_contour, -1, 1, 15)
ff_mask = np.zeros((gray.shape[0] + 2, gray.shape[1] + 2), 'uint8')
cv2.floodFill(ff, ff_mask, (int(gray.shape[1] / 2), int(gray.shape[0] / 2)), 1)
rect = maxRect(ff)
rectangle = [min(rect[0], rect[2]), max(rect[0], rect[2]), min(rect[1], rect[3]), max(rect[1], rect[3])]
img_crop = img[rectangle[0]:rectangle[1], rectangle[2]:rectangle[3]]
cv2.rectangle(ff, (min(rect[1], rect[3]), min(rect[0], rect[2])), (max(rect[1], rect[3]), max(rect[0], rect[2])), 3,
2)
return [img_crop, rectangle, tile_size]
def get_mask(ucm,viz=False):
ucm = ucm.copy()
h,w = ucm.shape[:2]
mask = np.zeros((h-2,w-2),'float32')
i = 0
sx,sy = np.where(mask==0)
seed = get_seed(sx,sy,ucm)
areas = []
labels=[]
while seed is not None and i<1000:
cv2.floodFill(mask,ucm,seed,i+1)
# calculate the area (no. of pixels):
areas.append(np.sum(mask==i+1))
labels.append(i+1)
# get the location of the next seed:
sx,sy = np.where(mask==0)
seed = get_seed(sx,sy,ucm)
i += 1
print " > terminated in %d steps"%i
if viz:
plt.imshow(mask)
plt.show()
return mask,np.array(areas),np.array(labels)
def _extract_arm(self, img):
# find center region of image frame (assume center region is 21 x 21 px)
center_half = 10 # (=(21-1)/2)
center = img[self.height/2 - center_half : self.height/2 + center_half, self.width/2 - center_half : self.width/2 + center_half]
# determine median depth value
median_val = np.median(center)
'''mask the image such that all pixels whose depth values
lie within a particular range are gray and the rest are black
'''
img = np.where(abs(img-median_val) <= self.abs_depth_dev, 128, 0).astype(np.uint8)
# Apply morphology operation to fill small holes in the image
kernel = np.ones((5,5), np.uint8)
img = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
# Find connected regions (to hand) to remove background objects
# Use floodfill with a small image area (7 x 7 px) that is set gray color value
kernel2 = 3
img[self.height/2-kernel2:self.height/2+kernel2, self.width/2-kernel2:self.width/2+kernel2] = 128
# a black mask to mask the 'non-connected' components black
mask = np.zeros((self.height + 2, self.width + 2), np.uint8)
floodImg = img.copy()
# Use floodFill function to paint the connected regions white
cv2.floodFill(floodImg, mask, (self.width/2, self.height/2), 255, flags=(4 | 255 << 8))
# apply a binary threshold to show only connected hand region
ret, floodedImg = cv2.threshold(floodImg, 129, 255, cv2.THRESH_BINARY)
return floodedImg
def update(dummy=None):
if seed_pt is None:
cv2.imshow('floodfill', img)
return
flooded = img.copy()
mask[:] = 0
lo = cv2.getTrackbarPos('lo', 'floodfill')
hi = cv2.getTrackbarPos('hi', 'floodfill')
flags = connectivity
if fixed_range:
flags |= cv2.FLOODFILL_FIXED_RANGE
cv2.floodFill(flooded, mask, seed_pt, (255, 255, 255), (lo,)*3, (hi,)*3, flags)
cv2.circle(flooded, seed_pt, 2, (0, 0, 255), -1)
cv2.imshow('floodfill', flooded)
def fill(th, im_th):
# Copy the thresholded image.
im_floodfill = im_th.copy()
# Mask used to flood filling.
# Notice the size needs to be 2 pixels than the image.
h, w = im_th.shape[:2]
mask = np.zeros((h+2, w+2), np.uint8)
# Floodfill from point (0, 0)
cv2.floodFill(im_floodfill, mask, (0,0), 255);
# Invert floodfilled image
im_floodfill_inv = cv2.bitwise_not(im_floodfill);
# Combine the two images to get the foreground.
im_out = im_th | im_floodfill_inv
return im_out;
def cropCircle(img):
'''
there many imaged taken thresholded, which means many images is
present as a circle with black surrounded. This function is to
find the largest inscribed rectangle to the thresholed image and
then crop the image to the rectangle.
input: img - the cv2 module
return: img_crop, rectangle, tile_size
'''
if(img.shape[0] > img.shape[1]):
tile_size = (int(img.shape[1]*256/img.shape[0]),256)
else:
tile_size = (256, int(img.shape[0]*256/img.shape[1]))
img = cv2.resize(img, dsize=tile_size)
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY);
_, thresh = cv2.threshold(gray, 10, 255, cv2.THRESH_BINARY)
_, contours, _ = cv2.findContours(thresh.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
main_contour = sorted(contours, key = cv2.contourArea, reverse = True)[0]
ff = np.zeros((gray.shape[0],gray.shape[1]), 'uint8')
cv2.drawContours(ff, main_contour, -1, 1, 15)
ff_mask = np.zeros((gray.shape[0]+2,gray.shape[1]+2), 'uint8')
cv2.floodFill(ff, ff_mask, (int(gray.shape[1]/2), int(gray.shape[0]/2)), 1)
rect = maxRect(ff)
rectangle = [min(rect[0],rect[2]), max(rect[0],rect[2]), min(rect[1],rect[3]), max(rect[1],rect[3])]
img_crop = img[rectangle[0]:rectangle[1], rectangle[2]:rectangle[3]]
cv2.rectangle(ff,(min(rect[1],rect[3]),min(rect[0],rect[2])),(max(rect[1],rect[3]),max(rect[0],rect[2])),3,2)
return [img_crop, rectangle, tile_size]
def cropCircle(img):
'''
there many imaged taken thresholded, which means many images is
present as a circle with black surrounded. This function is to
find the largest inscribed rectangle to the thresholed image and
then crop the image to the rectangle.
input: img - the cv2 module
return: img_crop, rectangle, tile_size
'''
if(img.shape[0] > img.shape[1]):
tile_size = (int(img.shape[1]*256/img.shape[0]),256)
else:
tile_size = (256, int(img.shape[0]*256/img.shape[1]))
img = cv2.resize(img, dsize=tile_size)
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY);
_, thresh = cv2.threshold(gray, 10, 255, cv2.THRESH_BINARY)
_, contours, _ = cv2.findContours(thresh.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
main_contour = sorted(contours, key = cv2.contourArea, reverse = True)[0]
ff = np.zeros((gray.shape[0],gray.shape[1]), 'uint8')
cv2.drawContours(ff, main_contour, -1, 1, 15)
ff_mask = np.zeros((gray.shape[0]+2,gray.shape[1]+2), 'uint8')
cv2.floodFill(ff, ff_mask, (int(gray.shape[1]/2), int(gray.shape[0]/2)), 1)
rect = maxRect(ff)
rectangle = [min(rect[0],rect[2]), max(rect[0],rect[2]), min(rect[1],rect[3]), max(rect[1],rect[3])]
img_crop = img[rectangle[0]:rectangle[1], rectangle[2]:rectangle[3]]
cv2.rectangle(ff,(min(rect[1],rect[3]),min(rect[0],rect[2])),(max(rect[1],rect[3]),max(rect[0],rect[2])),3,2)
return [img_crop, rectangle, tile_size]
def flood_fill_edges(img, stride):
"""
Check the strideth pixel along each edge of the image.
If it is white, floodfill the image black from that point.
"""
black = 0
white = 255
(rows, cols) = img.shape
msk = np.zeros((rows+2, cols+2, 1), np.uint8)
# Left and right edges
i = 0
while i < rows:
if img[i, 0] == white:
cv2.floodFill(img, msk, (0, i), black)
if img[i, cols-1] == white:
cv2.floodFill(img, msk, (cols-1, i), black)
i += stride
# Top and bottom edges
i = 0
while i < cols:
if img[0, i] == white:
cv2.floodFill(img, msk, (i, 0), black)
if img[rows-1, i] == white:
cv2.floodFill(img, msk, (i, rows-1), black)
i += stride