本文整理汇总了Python中cv2.adaptiveThreshold方法的典型用法代码示例。如果您正苦于以下问题:Python cv2.adaptiveThreshold方法的具体用法?Python cv2.adaptiveThreshold怎么用?Python cv2.adaptiveThreshold使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cv2
的用法示例。
在下文中一共展示了cv2.adaptiveThreshold方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: pre_process_image
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import adaptiveThreshold [as 别名]
def pre_process_image(img, skip_dilate=False):
"""Uses a blurring function, adaptive thresholding and dilation to expose the main features of an image."""
# Gaussian blur with a kernal size (height, width) of 9.
# Note that kernal sizes must be positive and odd and the kernel must be square.
proc = cv2.GaussianBlur(img.copy(), (9, 9), 0)
# Adaptive threshold using 11 nearest neighbour pixels
proc = cv2.adaptiveThreshold(proc, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)
# Invert colours, so gridlines have non-zero pixel values.
# Necessary to dilate the image, otherwise will look like erosion instead.
proc = cv2.bitwise_not(proc, proc)
if not skip_dilate:
# Dilate the image to increase the size of the grid lines.
kernel = np.array([[0., 1., 0.], [1., 1., 1.], [0., 1., 0.]],np.uint8)
proc = cv2.dilate(proc, kernel)
return proc
示例2: processImageForNeuralNet
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import adaptiveThreshold [as 别名]
def processImageForNeuralNet(arg1, image=False):
"""
Receives as parameter arg1 the path of the image to be converted or the image already captured with
cv2 (in that case, pass image=True as a parameter). The return of this function (x) should be passed as
input to a Network object by network.feedforward(x)
"""
SIDE_SIZE = 10
TOTAL_SIZE = 100
img = arg1
if(not image):
img = cv2.imread(arg1,0)
img = cv2.resize(img,(SIDE_SIZE,SIDE_SIZE))
img = cv2.adaptiveThreshold(img,1,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2)
img = np.reshape(img, (TOTAL_SIZE, 1))
return np.array(img, dtype='f')
示例3: normalize
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import adaptiveThreshold [as 别名]
def normalize(im):
"""Converts `im` to black and white.
Applying a threshold to a grayscale image will make every pixel either
fully black or fully white. Before doing so, a common technique is to
get rid of noise (or super high frequency color change) by blurring the
grayscale image with a Gaussian filter."""
im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
# Filter the grayscale image with a 3x3 kernel
blurred = cv2.GaussianBlur(im_gray, (3, 3), 0)
# Applies a Gaussian adaptive thresholding. In practice, adaptive thresholding
# seems to work better than appling a single, global threshold to the image.
# This is particularly important if there could be shadows or non-uniform
# lighting on the answer sheet. In those scenarios, using a global thresholding
# technique might yield paricularly bad results.
# The choice of the parameters blockSize = 77 and C = 10 is as much as an art
# as a science and domain-dependand.
# In practice, you might want to try different values for your specific answer
# sheet.
return cv2.adaptiveThreshold(
blurred, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 77, 10)
示例4: getSignature
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import adaptiveThreshold [as 别名]
def getSignature(img):
imgSize = np.shape(img)
gImg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Adaptive Thresholding requires the blocksize to be odd and bigger than 1
blockSize = 1 / 8 * imgSize[0] / 2 * 2 + 1
if blockSize <= 1:
blockSize = imgSize[0] / 2 * 2 + 1
const = 10
mask = cv2.adaptiveThreshold(gImg, maxValue = 255, adaptiveMethod = cv2.ADAPTIVE_THRESH_MEAN_C, thresholdType = cv2.THRESH_BINARY, blockSize = blockSize, C = const)
rmask = cv2.bitwise_not(mask)
return (cv2.bitwise_and(img, img, mask=rmask), rmask)
# First Prompt
示例5: clean_plate
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import adaptiveThreshold [as 别名]
def clean_plate(self, plate):
gray = cv2.cvtColor(plate, cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)
_, contours, _ = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
if contours:
areas = [cv2.contourArea(c) for c in contours]
max_index = np.argmax(areas) # index of the largest contour in the area array
max_cnt = contours[max_index]
max_cntArea = areas[max_index]
x,y,w,h = cv2.boundingRect(max_cnt)
rect = cv2.minAreaRect(max_cnt)
rotatedPlate = self.crop_rotated_contour(plate, rect)
if not self.ratioCheck(max_cntArea, rotatedPlate.shape[1], rotatedPlate.shape[0]):
return plate, False, None
return rotatedPlate, True, [x, y, w, h]
else:
return plate, False, None
示例6: read_file
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import adaptiveThreshold [as 别名]
def read_file(fname):
image = cv2.imread(fname,0)
image = cv2.adaptiveThreshold(image,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,2)
# cv2.namedWindow('image', cv2.WINDOW_NORMAL)
# cv2.imshow('image',image)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
# image = cv2.adaptiveThreshold(image,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2)
# cv2.imwrite("/home/ggdhines/temp.jpg",image)
# assert False
# _,image = cv2.threshold(image,200,255,cv2.THRESH_BINARY)
# image = 255 - image
# image = image > 0
image = image.astype(np.float)
return image
示例7: adaptiveThreshold
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import adaptiveThreshold [as 别名]
def adaptiveThreshold(plates):
for i, plate in enumerate(plates):
img = cv2.imread(plate)
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
cv2.imshow('gray', gray)
ret, thresh = cv2.threshold(gray, 50, 255, cv2.THRESH_BINARY)
# cv2.imshow('thresh', thresh)
threshMean = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 5, 10)
# cv2.imshow('threshMean', threshMean)
threshGauss = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 51, 27)
cv2.imshow('threshGauss', threshGauss)
cv2.imwrite("processed\\plate{}.png".format(i), threshGauss)
cv2.waitKey(0)
示例8: locate_text_area
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import adaptiveThreshold [as 别名]
def locate_text_area(pdf_image_row_block):
"""
locate the text area of the image row block
:param pdf_image_row_block: color pdf image block
:return:
"""
gray_image = cv2.cvtColor(pdf_image_row_block, cv2.COLOR_BGR2GRAY)
binarized_image = cv2.adaptiveThreshold(
src=gray_image,
maxValue=255,
adaptiveMethod=cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
thresholdType=cv2.THRESH_BINARY,
blockSize=11,
C=2
)
# sum along the col axis
col_sum = np.sum(binarized_image, axis=0)
idx_col_sum = np.argwhere(col_sum < col_sum.max())[:, 0]
start_col = idx_col_sum[0] if idx_col_sum[0] > 0 else 0
end_col = idx_col_sum[-1]
end_col = end_col if end_col < pdf_image_row_block.shape[1] else pdf_image_row_block.shape[1] - 1
return pdf_image_row_block[:, start_col:end_col, :]
示例9: _call_threshold
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import adaptiveThreshold [as 别名]
def _call_threshold(gray_img, threshold, max_value, threshold_method, method_name):
# Threshold the image
ret, bin_img = cv2.threshold(gray_img, threshold, max_value, threshold_method)
if bin_img.dtype != 'uint16':
bin_img = np.uint8(bin_img)
# Print or plot the binary image if debug is on
if params.debug == 'print':
print_image(bin_img, os.path.join(params.debug_outdir,
str(params.device) + method_name + str(threshold) + '.png'))
elif params.debug == 'plot':
plot_image(bin_img, cmap='gray')
return bin_img
# Internal method for calling the OpenCV adaptiveThreshold function to reduce code duplication
示例10: get_name
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import adaptiveThreshold [as 别名]
def get_name(img):
# cv2.imshow("method3", img)
# cv2.waitKey()
print('name')
_, _, red = cv2.split(img) #split 会自动将UMat转换回Mat
red = cv2.UMat(red)
red = hist_equal(red)
red = cv2.adaptiveThreshold(red, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 151, 50)
# red = cv2.medianBlur(red, 3)
red = img_resize(red, 150)
img = img_resize(img, 150)
# showimg(red)
# cv2.imwrite('name.png', red)
# img2 = Image.open('address.png')
# img = Image.fromarray(cv2.UMat.get(red).astype('uint8'))
#return get_result_vary_length(red, 'chi_sim', img, '-psm 7')
return get_result_vary_length(red, 'chi_sim', img, '--psm 7')
# return punc_filter(pytesseract.image_to_string(img, lang='chi_sim', config='-psm 13').replace(" ",""))
示例11: cartoonise
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import adaptiveThreshold [as 别名]
def cartoonise(self, img_rgb, num_down, num_bilateral, medianBlur, D, sigmaColor, sigmaSpace):
# 用高斯金字塔降低取样
img_color = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2BGR)
for _ in range(num_down):
img_color = cv2.pyrDown(img_color)
# 重复使用小的双边滤波代替一个大的滤波
for _ in range(num_bilateral):
img_color = cv2.bilateralFilter(img_color, d=D, sigmaColor=sigmaColor, sigmaSpace=sigmaSpace)
# 升采样图片到原始大小
for _ in range(num_down):
img_color = cv2.pyrUp(img_color)
if not self.Save_Edge:
img_cartoon = img_color
else:
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)
img_blur = cv2.medianBlur(img_gray, medianBlur)
img_edge = cv2.adaptiveThreshold(img_blur, 255,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY,
blockSize=self.Adaptive_Threshold_Block_Size,
C=self.C)
img_edge = cv2.cvtColor(img_edge, cv2.COLOR_GRAY2RGB)
img_edge = cv2.resize(img_edge, img_color.shape[:2][::-1])
img_cartoon = cv2.bitwise_and(img_color, img_edge)
return cv2.cvtColor(img_cartoon, cv2.COLOR_RGB2BGR)
示例12: processFile
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import adaptiveThreshold [as 别名]
def processFile(self, img, debug=False):
"""
Converts input image to grayscale & applies adaptive thresholding.
"""
img = cv2.GaussianBlur(img,(5,5),0)
# Convert to HSV
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# HSV Thresholding
res,hsvThresh = cv2.threshold(hsv[:,:,0], 25, 250, cv2.THRESH_BINARY_INV)
# Show adaptively thresholded image
adaptiveThresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 115, 1)
# Show both thresholded images
# cv2.imshow("HSV Thresholded",hsvThresh)
if debug:
cv2.imshow("Adaptive Thresholding", adaptiveThresh)
return img, adaptiveThresh
示例13: _get_image_segments
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import adaptiveThreshold [as 别名]
def _get_image_segments(image, kernel, block_size, c):
binarized_image = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY_INV, block_size, c)
labeled, nr_objects = ndimage.label(binarized_image, structure=kernel)
slices = ndimage.find_objects(labeled)
image_segments = {}
for idx, slice_ in enumerate(slices):
offset = instantiators['point'](slice_[1].start, slice_[0].start)
sliced_image = image[slice_]
boolean_array = labeled[slice_] == (idx+1)
segmented_image = 255- (255-sliced_image) * boolean_array
pixels = set(instantiators['point'](x, y) for x, y in np.transpose(np.nonzero(np.transpose(boolean_array))))
binarized_segmented_image = cv2.adaptiveThreshold(segmented_image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY_INV, block_size, c)
image_segment = ImageSegment(segmented_image, sliced_image, binarized_segmented_image, pixels, offset, idx)
image_segments[idx] = image_segment
return image_segments
示例14: PrepareImage
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import adaptiveThreshold [as 别名]
def PrepareImage(image):
"""Converts color image to black and white"""
# work on gray scale
bw = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
# remove noise, preserve edges
bw = cv2.bilateralFilter(bw, 9, 75, 75)
# binary threshold
bw = cv2.adaptiveThreshold(bw, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY, 11, 2)
return bw
示例15: gradient_and_binary
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import adaptiveThreshold [as 别名]
def gradient_and_binary(img_blurred, image_name='1.jpg', save_path='./'): # 将灰度图二值化,后面两个参数调试用
"""
求取梯度,二值化
:param img_blurred: 滤波后的图片
:param image_name: 图片名,测试用
:param save_path: 保存路径,测试用
:return: 二值化后的图片
"""
gradX = cv2.Sobel(img_blurred, ddepth=cv2.CV_32F, dx=1, dy=0)
gradY = cv2.Sobel(img_blurred, ddepth=cv2.CV_32F, dx=0, dy=1)
img_gradient = cv2.subtract(gradX, gradY)
img_gradient = cv2.convertScaleAbs(img_gradient) # sobel算子,计算梯度, 也可以用canny算子替代
# 这里改进成自适应阈值,貌似没用
img_thresh = cv2.adaptiveThreshold(img_gradient, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 3, -3)
# cv2.imwrite(os.path.join(save_path, img_name + '_binary.jpg'), img_thresh) # 二值化 阈值未调整好
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
img_closed = cv2.morphologyEx(img_thresh, cv2.MORPH_CLOSE, kernel)
img_closed = cv2.morphologyEx(img_closed, cv2.MORPH_OPEN, kernel)
img_closed = cv2.erode(img_closed, None, iterations=9)
img_closed = cv2.dilate(img_closed, None, iterations=9) # 腐蚀膨胀
# 这里调整了kernel大小(减小),腐蚀膨胀次数后(增大),出错的概率大幅减小
return img_closed