Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
image = rd.LoadGDAL(in_sink)
no_data_raw, projection, geotransform, resolution = getMetadata(image)
rows_cols = image.shape
print("rows, cols: " + str(rows_cols))
print("Pixel resolution: " + str(resolution))
print("Read data time: {:.4f} seconds".format(time.time() - read_time))
min_elev, max_elev, no_data = get_min_max_nodata(image) # set nodata value to a large value, e.g., 9999
# initialize output image
obj_image = np.zeros(image.shape) # output depression image with unique id for each nested depression
level_image = np.zeros(image.shape) # output depression level image
# nb_labels is the total number of objects. 0 represents background object.
label_objects, nb_labels = regionGroup(image, min_size, no_data)
regions = measure.regionprops(label_objects, image, coordinates='xy')
del image # delete the original image to save memory
prep_time = time.time()
print("Data preparation time: {:.4f} seconds".format(prep_time - init_time))
print("Total number of regions: {}".format(nb_labels))
identify_time = time.time()
obj_uid = 0
global_dep_list = []
# loop through regions and identify nested depressions in each region using level-set method
for region in regions: # iterate through each depression region
region_id = region.label
img = region.intensity_image # dem subset for each region
bbox = region.bbox
def frame_features(self, frame, dt):
img_label = self.labels[frame, :, :].copy()
features_temp = []
for j in range(self.channels):
features_temp.append(regionprops(img_label, self.images[j][frame, :, :]))
feature_mat = np.zeros((len(features_temp[0]), self.feature_num))
img_new = np.zeros(img_label.shape)
for j in range(len(features_temp[0])):
cell_temp = features_temp[0][j]
features_vector = np.zeros(self.feature_num)
ypos = cell_temp.centroid[0]
xpos = cell_temp.centroid[1]
features_vector[0] = self.counter
features_vector[1] = frame
features_vector[2] = xpos
def identify_boundary_objects(self, a_license_plate):
labelImage = measure.label(a_license_plate)
character_dimensions = (0.4*a_license_plate.shape[0], 0.85*a_license_plate.shape[0], 0.04*a_license_plate.shape[1], 0.15*a_license_plate.shape[1])
minHeight, maxHeight, minWidth, maxWidth = character_dimensions
regionLists = regionprops(labelImage)
return regionLists
branches = sp.ndimage.binary_dilation(
branches,
structure=skimage.morphology.disk(b_dilation)
)
m_mask = m_mask | branches
# set a dictionary
m_dict = defaultdict(list)
if theta > 0:
# set degrees between line segments
degrees = np.arange(360/theta)*theta
# perform regionprop for each nuclei
rprops = skimage.measure.regionprops(h_label)
numLabels = len(rprops)
for i in range(numLabels):
# find centroids for nuclei
cx = rprops[i].centroid[0].astype(int)
cy = rprops[i].centroid[1].astype(int)
# remove cx, cy crossing over membrane_mask
if m_mask[cx, cy] is False:
# find end points
endx = cx + np.round(length * np.cos(np.radians(degrees)))
endy = cy + np.round(length * np.sin(np.radians(degrees)))
labels = []
dep_list.append(Depression(unique_id, level, cells, size, volume, mean_depth, max_depth, min_elev, max_elev, [],
region_id, perimeter, major_axis, minor_axis, elongatedness, eccentricity,
orientation, area_bbox_ratio))
level_img = np.ones(img.shape)
del img
return level_img, dep_list
for elev in np.arange(max_elev, min_elev, interval): # slicing operation using top-down approach
img[img > elev] = 0 # set elevation higher than xy-plane to zero
label_objects, nb_labels = regionGroup(img, min_size, no_data)
# print('slicing elev = {:.2f}, number of objects = {}'.format(elev, nb_labels))
if nb_labels == 0: # if slicing results in no objects, quit
break
objects = measure.regionprops(label_objects, img, coordinates='xy')
for i, object in enumerate(objects):
(row, col) = object.coords[0] # get a boundary cell
bbox = object.bbox
if len(parent_ids) == 0: # This is the first depression, maximum depression
# print("This is the maximum depression extent.")
cells = object.area
size = cells * pow(resolution, 2) # depression size
max_depth = object.max_intensity - object.min_intensity # depression max depth
mean_depth = (object.max_intensity * cells - np.sum(object.intensity_image)) / cells # depression mean depth
volume = mean_depth * cells * pow(resolution, 2) # depression volume
# spill_elev = object.max_intensity # to be implemented
min_elev = object.min_intensity # depression min elevation
max_elev = object.max_intensity # depression max elevation
# print("size = {}, max depth = {:.2f}, mean depth = {:.2f}, volume = {:.2f}, spill elev = {:.2f}".format(
# size, max_depth, mean_depth, volume, spill_elev))
# Get sorted `skimage` regions for column masks
col_regions = utils.sort_regions(
measure.regionprops(col_labels), self.layout_params["order"]
)
# Figure out crop endpoints, set related args
crop_axis = 0 if self.layout_params["orientation"] == "l2r" else 1
# Set up `endpts` for bbox adjustment
if self.endpts_is_auto:
if self.layout_params["endpts"] == "auto":
regions = col_regions
else:
# 'auto_all' mode
regions = measure.regionprops(utils.masks_to_labels(preds["masks"]))
endpts = utils.maximum_extent(regions, crop_axis)
elif self.endpts_is_class:
measure_idxs = np.where(preds["class_ids"] == self.endpts_class_id)[0]
# If object not detected, then ignore for cropping
if measure_idxs.size == 0:
print("`endpts` class not detected, cropping will use `auto` method")
regions = col_regions
# Otherwise, use bbox of instance with highest confidence score
else:
best_idx = measure_idxs[np.argmax(preds["scores"][measure_idxs])]
regions = measure.regionprops(
(preds["masks"][:, :, best_idx]).astype(np.int)
def judge(img): #判断能否识别验证码
img = img[97:,:]
img=gaussian(img, sigma=0.85)
img=equalize_hist(img)
img=(img > 0.7)*1.0
img=opening(img,selem=np.array([[0,1,0],[1,1,1],[0,1,0]]))
image_region=img*0
img=label(img,connectivity=1)
props = regionprops(img)
cnt=0
centerx=[]
width=[]
for i in range(np.max(img)):
if props[i]['area'] > 290:
image_region = image_region + (img==props[i]['label'])
centerx.append(props[i]['centroid'][1])
width.append(props[i]['image'].shape[1])
cnt += 1
# 八个连通域
if cnt != 8:
return False
# 连通域之间距离;宽高比
centerx.sort()
if np.std(np.diff(np.array(centerx))) > 10 or np.min(np.array(width)) < 18:
return False
def filter_fiber(blobs):
objects = [(obj.area, obj.eccentricity, obj.label) for obj in regionprops(blobs)]
objects = sorted(objects, reverse=True) # sorted by area in descending order
# filter out the largest one which is (1) 5 times larger than 2nd largest one (2) eccentricity > 0.95
if len(objects) > 1 and objects[0][0] > 5 * objects[1][0] and objects[0][1] > 0.95:
print('\nfilter suspecious fiber', objects[0])
blobs = np.where(blobs==objects[0][2], 0, blobs)
return blobs
single_images = []
img = np.copy(level_img)
digits = int(math.log10(max_level)) + 1 # determine the level number of output file name
for i in range(1, max_level + 1):
img[(img > 0) & (img <= i) ] = i
tmp_img = np.copy(img)
tmp_img[tmp_img > i] = 0
if bool_comb == True: # whether to extract combined level image
combined_images.append(np.copy(tmp_img))
filename_combined = "Combined_level_" + str(i).zfill(digits) + ".tif"
out_file = os.path.join(out_shp_dir, filename_combined)
writeRaster(tmp_img,out_file,template)
lbl_objects, n_labels = regionGroup(tmp_img, min_size, no_data)
regs = measure.regionprops(lbl_objects, level_img, coordinates='xy')
regs2 = measure.regionprops(lbl_objects, obj_img, coordinates='xy')
sin_img = np.zeros(img.shape)
for index, reg in enumerate(regs):
uid = regs2[index].min_intensity
if reg.max_intensity >= i:
bbox = reg.bbox
tmp_img = np.zeros(reg.image.shape)
tmp_img[reg.image] = uid
writeObject(sin_img, tmp_img, bbox)
# for reg in regs:
# if reg.max_intensity >= i:
# bbox = reg.bbox
# tmp_img = np.zeros(reg.image.shape)
#label_small = np.where(flag_slabel)[0]
#for i in label_small:
# label_img[label_img == i] = 0
mask = morph.remove_small_objects(label_img, min_size=min_area, connectivity=1)
label_img[mask == 0] = 0
label_img, num_label = measure.label(label_img, connectivity=1, return_num=True) # re-label
# remove regions that would disappear after erosion operation
erosion_structure = np.ones((erosion_size, erosion_size))
label_erosion_img = morph.erosion(label_img, erosion_structure).astype(np.uint8)
erosion_regions = measure.regionprops(label_erosion_img)
if len(erosion_regions) < num_label:
if print_msg:
print('Some regions are lost during morphological erosion operation')
label_erosion = [reg.label for reg in erosion_regions]
for orig_reg in measure.regionprops(label_img):
if orig_reg.label not in label_erosion:
if print_msg:
print('label: {}, area: {}, bbox: {}'.format(orig_reg.label,
orig_reg.area,
orig_reg.bbox))
label_img[label_img == orig_reg.label] = 0
label_img, num_label = measure.label(label_img, connectivity=1, return_num=True) # re-label
# get label boundaries to facilitate bridge finding
if get_boundary:
label_bound = seg.find_boundaries(label_erosion_img, mode='thick').astype(np.uint8)
label_bound *= label_erosion_img
return label_img, num_label, label_bound
else:
return label_img, num_label