def _extraction_iterator_corners(image, use_local_thresholding=False, apply_gaussian=False, n=5):
# If the image is too small, then double its scale until big enough.
img = image
while max(img.shape) < 500:
img = resize(img, np.array(img.shape) * 2)
if apply_gaussian:
img = gaussian_filter(image, (3.0, 3.0))
for corner_points in iter_blob_extremes(img, n=n):
try:
warped_image = geometry.warp_image_by_corner_points_projection(corner_points, img)
sudoku, bin_image = geometry.split_image_into_sudoku_pieces_adaptive_global(
warped_image, otsu_local=use_local_thresholding, apply_gaussian=apply_gaussian)
except SudokuExtractError:
# Try next blob.
pass
except Exception as e:
raise
else:
yield sudoku, bin_image
python类gaussian_filter()的实例源码
def _extraction_iterator_map(image, use_local_thresholding=False, apply_gaussian=False, n=5):
if apply_gaussian:
img = gaussian_filter(image, (3.0, 3.0))
else:
img = image
for edges in iter_blob_contours(img, n=n):
try:
warped_image = geometry.warp_image_by_interp_borders(edges, img)
sudoku, bin_image = geometry.split_image_into_sudoku_pieces_adaptive_global(
warped_image, otsu_local=use_local_thresholding, apply_gaussian=apply_gaussian)
except SudokuExtractError as e:
pass
except Exception as e:
# Try next blob
raise
else:
yield sudoku, bin_image
def to_binary_adaptive(img):
sigma = 1.0
m = max(img.shape)
if m > 2000:
block_size = 80
elif m > 1500:
block_size = 50
elif m > 1000:
block_size = 35
else:
block_size = 20
bimg = gaussian_filter(img, sigma=sigma)
bimg = threshold_adaptive(bimg, block_size, offset=2 / 255)
bimg = np.array(bimg, 'uint8') * 255
return bimg
def split_image_into_sudoku_pieces_adaptive_global(image, otsu_local=False, apply_gaussian=False):
L = image.shape[0]
d = int(np.ceil(L / 9))
dd = d // 5
output = []
if apply_gaussian:
image = gaussian_filter(image, sigma=1.0)
if not otsu_local:
image = to_binary_adaptive(image)
for k in range(9):
this_row = []
start_row_i = max([k * d - dd, 0])
stop_row_i = min([(k + 1) * d + dd, L])
for kk in range(9):
start_col_i = max([kk * d - dd, 0])
stop_col_i = min([(kk + 1) * d + dd, L])
i = image[start_row_i:stop_row_i, start_col_i:stop_col_i].copy()
if otsu_local:
i = to_binary_otsu(i)
i = binary_opening(i)
i = to_binary_otsu(i)
if apply_gaussian:
i = to_binary_otsu(binary_dilation(i))
this_row.append(i)
output.append(this_row)
return output, image
def gaussianFilter(img,sigma=2.,debug=False,axes=None):
"""Applies gaussian filter to image.
Args:
img (numpy.ndarray): Input image.
Keyword Args:
sigma (float): Standard deviation of gaussian kernel applied.
axes (list): List of matplotlib axes used for plotting. If not specified, will generate new ones.
debug (bool): Print debugging messages and show debugging plots.
Returns:
numpy.ndarray: Processed image.
"""
#Grab original image
orgImg=img.copy()
#Apply gaussian filter
try:
img = skifilt.gaussian_filter(img,sigma)
except AttributeError:
img = skifilt.gaussian(img,sigma)
#Debugging plots
if debug:
#Make figure
if axes==None:
fig,axes = pyfrp_plot_module.makeSubplot([2,2],titles=["Original Image", "After gaussian","Histogram Original","Histogram gaussian"],sup="gaussianFilter debugging output")
#Get common range
vmin,vmax=getCommonRange([orgImg,img])
showImgAndHist(orgImg,axes=axes[0:2],vmin=vmin,vmax=vmax)
showImgAndHist(img,axes=axes[2:],vmin=vmin,vmax=vmax)
return img
def dslre(img):
timestep = 1.0
mu = 0.2/timestep
iter_basic = 1000
iter_refine = 10
lambdap = 5
alpha = 1.5 # -3
epsilon = 1.5
sigma = 1.5
smoothed = filters.gaussian_filter(img,sigma)
dy,dx = np.gradient(smoothed)
mag = (dx**2)+(dy**2)
edge = 1.0/(1.0+mag)
c0 = 2
initialLSF = c0*np.ones(img.shape)
initialLSF[10:50,10:50] = -c0
#initialLSF[10:55,10:75] = -c0
#initialLSF[25:35,20:25] -= c0
#initialLSF[25:35,40:50] -= c0
phi = initialLSF
drlse_edge(phi,edge,lambdap,mu,alpha,epsilon,timestep,iter_basic)
drlse_edge(phi,edge,lambdap,mu,0,epsilon,timestep,iter_refine)
return phi
def get_candidate_symbol_regions(image, text_regions, updated_width, updated_height):
img = skimage.io.imread(image.name)[:, :, :3]
if not (updated_height == len(img) and updated_width == len(img[0])):
img = skimage.transform.resize(img, (updated_height, updated_width))
symbol_regions = dict()
for x, y, w, h in text_regions:
text_region_image = img[y: y + h, x: x + w]
text_region_image_width = len(text_region_image[0])
text_region_image_height = len(text_region_image)
text_region_gray_image = skimage.color.rgb2gray(text_region_image)
text_region_binary_image = image <= threshold_otsu(text_region_gray_image)
temp = TemporaryFile(".png")
skimage.io.imsave(temp.name, text_region_binary_image)
text_region_binary_image = skimage.io.imread(temp.name)
text_region_blurred_image = gaussian_filter(text_region_binary_image, sigma=3.5)
text_region_blobs = text_region_blurred_image > text_region_blurred_image.mean()
text_region_labels = skimage.morphology.label(text_region_blobs, neighbors=4)
symbol_blobs = ndimage.find_objects(text_region_labels)
candidate_symbol_regions = set()
for c1, c2 in symbol_blobs:
if (c2.stop - c2.start) * c1.stop - c1.start > (text_region_image.shape[0] * text_region_image.shape[1]) * (0.026):
if (c2.stop - c2.start) * c1.stop - c1.start < (text_region_image.shape[0] * text_region_image.shape[1]) * (0.90):
candidate_symbol_regions.add(
(c2.start, c1.start, c2.stop - c2.start, c1.stop - c1.start))
symbol_regions[str((x, y, w, h))] = dict()
symbol_regions[str((x, y, w, h))]["image"] = text_region_image
symbol_regions[str((x, y, w, h))]["regions"] = candidate_symbol_regions
symbol_regions[str((x, y, w, h))]["width"] = text_region_image_width
symbol_regions[str((x, y, w, h))]["height"] = text_region_image_height
return symbol_regions
def iter_blob_extremes(image, n=5):
original_shape = image.shape[::-1]
if max(original_shape) < 2000:
size = (500, 500)
y_scale = original_shape[0] / 500
x_scale = original_shape[1] / 500
else:
size = (1000, 1000)
y_scale = original_shape[0] / 1000
x_scale = original_shape[1] / 1000
img = resize(image, size)
bimg = gaussian_filter(img, sigma=1.0)
bimg = threshold_adaptive(bimg, 20, offset=2/255)
bimg = -bimg
bimg = ndi.binary_fill_holes(bimg)
label_image = label(bimg, background=False)
label_image += 1
regions = regionprops(label_image)
regions.sort(key=attrgetter('area'), reverse=True)
iter_n = 0
for region in regions:
try:
iter_n += 1
if iter_n > n:
break
# Skip small images
if region.area < int(np.prod(size) * 0.05):
continue
coords = get_contours(add_border(label_image == region.label,
size=label_image.shape,
border_size=1,
background_value=False))[0]
coords = np.fliplr(coords)
top_left = sorted(coords, key=lambda x: np.linalg.norm(np.array(x)))[0]
top_right = sorted(coords, key=lambda x: np.linalg.norm(np.array(x) - [img.shape[1], 0]))[0]
bottom_left = sorted(coords, key=lambda x: np.linalg.norm(np.array(x) - [0, img.shape[0]]))[0]
bottom_right = sorted(coords, key=lambda x: np.linalg.norm(np.array(x) - [img.shape[1], img.shape[0]]))[0]
scaled_extremes = [(int(x[0] * y_scale), int(x[1]*x_scale)) for x in (top_left, top_right, bottom_left, bottom_right)]
yield scaled_extremes
except Exception:
pass
raise SudokuExtractError("No suitable blob could be found.")