def compositeThreshold(gray, mode='com'): if mode == 'otsu': otsu = threshold_otsu(gray) otsu_bin = gray > otsu otsu_bin = otsu_bin.astype(np.uint8) * 255 return otsu_bin elif mode == 'yen': yen = threshold_yen(gray) yen_bin = gray > yen yen_bin = yen_bin.astype(np.uint8) * 255 return yen_bin elif mode == 'li': li = threshold_li(gray) li_bin = gray > li li_bin = li_bin.astype(np.uint8) * 255 return li_bin elif mode == 'niblack': niblack = threshold_niblack(gray, window_size=13, k=0.8) niblack_bin = gray > niblack niblack_bin = niblack_bin.astype(np.uint8) * 255 return niblack_bin elif mode == 'sauvola': sauvola = threshold_sauvola(gray, window_size=13) sauvola_bin = gray > sauvola sauvola_bin = sauvola_bin.astype(np.uint8) * 255 return sauvola_bin elif mode == 'com': li = threshold_li(gray) li_bin = gray > li li_bin = li_bin.astype(np.uint8) * 255 otsu = threshold_otsu(gray) otsu_bin = gray > otsu otsu_bin = otsu_bin.astype(np.uint8) * 255 yen = threshold_yen(gray) yen_bin = gray > yen yen_bin = yen_bin.astype(np.uint8) * 255 return cv2.min(cv2.min(otsu_bin, li_bin), yen_bin) elif mode == "niblack-multi": thr = np.zeros((gray.shape), dtype=np.uint8) thr[thr >= 0] = 255 for k in np.linspace(-0.8, 0.2, 5): #(-1.8,0.2,5) thresh_niblack = threshold_niblack(gray, window_size=25, k=k) binary_niblack = gray > thresh_niblack binary_niblack = binary_niblack.astype(np.uint8) * 255 showResult("binary_niblack", binary_niblack) thr = cv2.min(thr, binary_niblack) return thr else: sauvola = threshold_sauvola(gray, window_size=25, k=0.25) sauvola_bin = gray > sauvola sauvola_bin = sauvola_bin.astype(np.uint8) * 255 niblack = threshold_niblack(gray, window_size=25, k=0.25) niblack_bin = gray > niblack niblack_bin = niblack_bin.astype(np.uint8) * 255 return cv2.max(sauvola, niblack)
def threshold(image, *, sigma=0., radius=0, offset=0., method='sauvola', smooth_method='Gaussian'): """Use scikit-image filters to "intelligently" threshold an image. Parameters ---------- image : array, shape (M, N, ...[, 3]) Input image, conformant with scikit-image data type specification [1]_. sigma : float, optional If positive, use Gaussian filtering to smooth the image before thresholding. radius : int, optional If given, use local median thresholding instead of global. offset : float, optional If given, reduce the threshold by this amount. Higher values result in fewer pixels above the threshold. method: {'sauvola', 'niblack', 'median'} Which method to use for thresholding. Sauvola is 100x faster, but median might be more accurate. smooth_method: {'Gaussian', 'TV'} Which method to use for smoothing. Choose from Gaussian smoothing and total variation denoising. Returns ------- thresholded : image of bool, same shape as `image` The thresholded image. References ---------- .. [1] http://scikit-image.org/docs/dev/user_guide/data_types.html """ if sigma > 0: if smooth_method.lower() == 'gaussian': image = filters.gaussian(image, sigma=sigma) elif smooth_method.lower() == 'tv': image = restoration.denoise_tv_bregman(image, weight=sigma) if radius == 0: t = filters.threshold_otsu(image) + offset else: if method == 'median': footprint = hyperball(image.ndim, radius=radius) t = ndi.median_filter(image, footprint=footprint) + offset elif method == 'sauvola': w = 2 * radius + 1 t = threshold_sauvola(image, window_size=w, k=offset) elif method == 'niblack': w = 2 * radius + 1 t = threshold_niblack(image, window_size=w, k=offset) else: raise ValueError('Unknown method %s. Valid methods are median,' 'niblack, and sauvola.' % method) thresholded = image > t return thresholded
def fit(self, X=None, y=None): if self.threshold_type == "otsu": threshold_function = lambda data: filters.threshold_otsu(data) elif self.threshold_type == "local_otsu": threshold_function = lambda data: filters.rank.otsu(data, morphology.square(self.block_size)) elif self.threshold_type == "local": threshold_function = lambda data: filters.threshold_local(data, self.block_size) elif self.threshold_type == "niblack": threshold_function = lambda data: filters.threshold_niblack(data, self.block_size) elif self.threshold_type == "sauvola": threshold_function = lambda data: filters.threshold_sauvola(data, self.block_size) elif self.threshold_type is None: threshold_function = None else: raise ValueError("Unknown threshold type: {}".format(self.threshold_type)) self.ocr_reader_ = screen_ocr.Reader.create_reader( backend=self.backend, threshold_function=threshold_function, correction_block_size=self.correction_block_size, margin=self.margin, resize_factor=self.resize_factor, resize_method=self.resize_method, convert_grayscale=self.convert_grayscale, shift_channels=self.shift_channels, label_components=self.label_components, debug_image_callback=None)
def main(img, ws): image = img binary_global = image > threshold_otsu(image) window_size = ws thresh_niblack = threshold_niblack(image, window_size=window_size, k=0.8) thresh_sauvola = threshold_sauvola(image, window_size=window_size) binary_niblack = image > thresh_niblack binary_sauvola = image > thresh_sauvola plt.figure(figsize=(8, 7)) plt.subplot(2, 2, 1) plt.imshow(image, cmap=plt.cm.gray) plt.title('Original') plt.axis('off') plt.subplot(2, 2, 2) plt.title('Global Threshold') plt.imshow(binary_global, cmap=plt.cm.gray) plt.axis('off') plt.subplot(2, 2, 3) plt.imshow(binary_niblack, cmap=plt.cm.gray) plt.title('Niblack Threshold') plt.axis('off') plt.subplot(2, 2, 4) plt.imshow(binary_sauvola, cmap=plt.cm.gray) plt.title('Sauvola Threshold') plt.axis('off') return plt, binary_global, binary_niblack, binary_sauvola
def Binarization_Niblack(image, window_size, k): thresh_niblack = threshold_niblack(image, window_size=window_size, k=k) binary_niblack = image > thresh_niblack binary_niblack = binary_niblack.astype(np.float32) binary_niblack = binary_niblack * 255 binary_niblack = 255 - binary_niblack return binary_niblack
def raw_stretch_to_jpg(raw_filename, jpg_filename): out_raw_hist_p = -1.0 out_str_hist_p = -1.0 out_is_under_exp = True out_is_over_exp = True # Reference https://www.kaggle.com/tsilveira/raw-image-processing # Documentation https://scikit-image.org/docs/stable/index.html # I tried a few things out and found the following gets a good auto-stretch where stars and nebula are visible. # 1. adjust gamma, gamma=1, gain=1 # 2. equalize histogram # 3. niblack threshold, window_size=9, k=1 (high window = blur, high k = darker with diminishing returns) # The goal is just to have a small reference image to send to Discord for checking drift over time without going outside.. # It is NOT a goal to have a usable stretched image. There is much better software and it requires human input. with rawpy.imread(raw_filename) as rawImg: rgbImg = rawImg.raw_image_visible gImg = exposure.adjust_gamma(rgbImg, gamma=1, gain=1) ghImg = exposure.equalize_hist(gImg) nibImg = filters.threshold_niblack(ghImg, window_size=9, k=1) # TODO look into streaming to requests instead of writing a file imageio.imwrite(jpg_filename, nibImg) # histogram calculations out_raw_hist_p, out_is_under_exp, out_is_over_exp = peak_histogram_percentage( rgbImg) out_str_hist_p, _, _ = peak_histogram_percentage(nibImg) return out_raw_hist_p, out_str_hist_p, out_is_under_exp, out_is_over_exp
def main(): image = cv2.imread("./counter_images/01305.png", cv2.IMREAD_GRAYSCALE) # image = cv2.imread("../venv/lib/python3.7/site-packages/skimage/data/page.png", cv2.IMREAD_GRAYSCALE) image = 255 - image image = cv2.medianBlur(image, 7) binary_global = image > threshold_otsu(image) binary_global = np.uint8(binary_global * 255) window_size = 41 thresh_niblack = threshold_niblack(image, window_size=window_size, k=0.8) thresh_sauvola = threshold_sauvola(image, window_size=window_size, k=.1) binary_niblack = image > thresh_niblack binary_niblack = np.uint8(binary_niblack * 255) binary_sauvola = image > thresh_sauvola binary_sauvola = np.uint8(binary_sauvola * 255) imshowWait(image=image, binary_global=binary_global, binary_niblack=binary_niblack, binary_sauvola=binary_sauvola)
def doThresholding(method, window_size, k, img): if method == 'niblack': th_mask = threshold_niblack(img, window_size=window_size, k=k) if method == 'sauvola': th_mask = threshold_sauvola(img, window_size=window_size) binary_mask = img < th_mask return(binary_mask)
def ThreSegment(self, SideLength, ThreK): pix = array(self.__im) thresh_pix = threshold_niblack(pix, window_size=SideLength * SideLength, k=ThreK) binary_pix = pix > thresh_pix pix = binary_pix.astype(int) * 255 self.__im = fromarray(pix)
def threshold_niblack(arr1d): """ doesnt work: TypeError: ndarray() missing required argument 'shape' (pos 1) :param arr1d: :return: """ import skimage.filters as sf thresh = sf.threshold_niblack(arr1d, window_size=15, k=0.2) return thresh
def refineCrop(sections, width=16): new_sections = [] for section in sections: cv2.blur(section, (3, 3), 3) sec_center = np.array([section.shape[1] / 2, section.shape[0] / 2]) thresh_niblack = threshold_niblack(section, window_size=17, k=-0.2) binary_niblack = section > thresh_niblack binary_niblack = binary_niblack.astype(np.uint8) * 255 imagex, contours, hierarchy = cv2.findContours(binary_niblack, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) boxs = [] for contour in contours: x, y, w, h = cv2.boundingRect(contour) ratio = w / float(h) if ratio < 1 and h > 36 * 0.4 and y < 16: box = [x, y, w, h] boxs.append([box, np.array([x + w / 2, y + h / 2])]) # cv2.rectangle(section,(x,y),(x+w,y+h),255,1) # print boxs dis_ = np.array([((one[1] - sec_center)**2).sum() for one in boxs]) if len(dis_) == 0: kernal = [0, 0, section.shape[1], section.shape[0]] else: kernal = boxs[dis_.argmin()][0] center_c = (kernal[0] + kernal[2] / 2, kernal[1] + kernal[3] / 2) w_2 = int(width / 2) h_2 = kernal[3] / 2 if center_c[0] - w_2 < 0: w_2 = center_c[0] new_box = [center_c[0] - w_2, kernal[1], width, kernal[3]] # print new_box[2]/float(new_box[3]) if new_box[2] / float(new_box[3]) > 0.6: # print "异常" h = int((new_box[2] / 0.35) / 2) if h > 35: h = 35 new_box[1] = center_c[1] - h if new_box[1] < 0: new_box[1] = 1 new_box[3] = h * 2 section = section[new_box[1]:new_box[1] + new_box[3], new_box[0]:new_box[0] + new_box[2]] # cv2.imshow("section",section) # cv2.waitKey(0) new_sections.append(section) # print new_box return new_sections
def binarize(cls, images: List[bytes], method: Method) -> (List[bytes], str): if method == Method.SAUVOLA or method == Method.UNSET: return cls._binarize( images, lambda x: threshold_sauvola(x, window_size=25)) elif method == Method.NIBLACK: return cls._binarize( images, lambda x: threshold_niblack(x, window_size=25, k=0.8)) else: return cls._binarize(images, lambda x: threshold_otsu(x))
def test_abstract_painting(): out_dir = '../output_data/abstract_painting_nopadding/' img = lm(cv2.imread(config['image_paths']['original'])) start_num = 1 for t in tqdm(range(11, 151, 2)): #padded_counter = pad_int(t, 3) thresholded = threshold_niblack(img, t) segmented = (img < thresholded).astype(int) segmented = stretch_histogram(segmented) cv2.imwrite(os.path.join(out_dir, str(start_num) + '.jpg'), segmented) start_num += 1
def thre_segment(img, sidelength, threk): """局部阈值分割 :param img:输入图像 :param sidelength:Niblack模板边长 :param threk:补偿权值 :return:输出图像 """ thresh_niblack = threshold_niblack(img, window_size=sidelength, k=threk) binary_niblack = img > thresh_niblack seg_img = binary_niblack.astype(int) * 255 res = np.uint8(seg_img) return res
def make_segment(case_nr, params): img = plt.imread(R"result\r{}.png".format(case_nr)) img_hsv = clr.rgb2hsv(img) img_value = img_hsv[:, :, 2] v_std = np.std(img_value) img_value = (img_value - params[0]) * (params[1] / v_std) manipulation = np.abs(img_value) if params[2] == 0: thresh = flt.threshold_otsu(manipulation) binary = manipulation > thresh elif params[2] == 1: thresh = flt.threshold_isodata(manipulation) binary = manipulation > thresh elif params[2] == 2: thresh = flt.threshold_li(manipulation) binary = manipulation > thresh elif params[2] == 3: thresh = flt.threshold_mean(manipulation) binary = manipulation > thresh elif params[2] == 4: thresh = flt.threshold_niblack(manipulation) binary = manipulation > thresh elif params[2] == 5: thresh = flt.threshold_sauvola(manipulation) binary = manipulation > thresh elif params[2] == 6: thresh = flt.threshold_triangle(manipulation) binary = manipulation > thresh else: thresh = flt.threshold_yen(manipulation) binary = manipulation > thresh binary = morph.remove_small_holes(binary, area_threshold=100) binary = morph.remove_small_objects(binary, min_size=70, connectivity=2) return binary
def get_binary(args, image, file: str, binpath: str) -> str: """ Binarize image with different algorithms :param args: :param image: :param file: :param binpath: :return: """ if not os.path.exists(binpath + file.split('/')[-1]): create_dir(binpath) uintimage = get_uintimg(image) if args.filter == "sauvola": thresh = imgfilter.threshold_sauvola(uintimage, args.threshwindow, args.threshweight) binary = image > thresh elif args.filter == "niblack": thresh = imgfilter.threshold_niblack(uintimage, args.threshwindow, args.threshweight) binary = thresh elif args.filter == "otsu": thresh = imgfilter.threshold_otsu(uintimage, args.threshbin) binary = image <= thresh elif args.filter == "yen": thresh = imgfilter.threshold_yen(uintimage, args.threshbin) binary = image <= thresh elif args.filter == "triangle": thresh = imgfilter.threshold_triangle(uintimage, args.threshbin) binary = image > thresh elif args.filter == "isodata": thresh = imgfilter.threshold_isodata(uintimage, args.threshbin) binary = image > thresh elif args.filter == "minimum": thresh = imgfilter.threshold_minimum(uintimage, args.threshbin, args.threshitter) binary = image > thresh elif args.filter == "li": thresh = imgfilter.threshold_li(uintimage) binary = image > thresh elif args.filter == "mean": thresh = imgfilter.threshold_mean(uintimage) binary = image > thresh else: binary = uintimage with warnings.catch_warnings(): # Transform rotate convert the img to float and save convert it back warnings.simplefilter("ignore") misc.imsave(binpath + file.split('/')[-1], binary) return binpath + file.split('/')[-1]
def thr_conn(img,fname,stfolder,sfn,thrtyp,bs,mp,kv,rv,inv,ext,prev): ofs=-5 if thrtyp=='Gauss': tmp=cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, bs, ofs) thrconnimg=Image.fromarray(tmp,mode='L') if thrtyp=='Mean': tmp=cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, bs, ofs) thrconnimg=Image.fromarray(tmp,mode='L') if thrtyp=='Gauss Sk': ad_thr = threshold_local(img, bs,method='gaussian', offset=ofs) tmp = 255*(img > ad_thr).astype('uint8') thrconnimg=Image.fromarray(tmp,mode='L') if thrtyp=='Mean Sk': ad_thr = threshold_local(img, bs,method='mean', offset=ofs) tmp = 255*(img > ad_thr).astype('uint8') thrconnimg=Image.fromarray(tmp,mode='L') if thrtyp=='Median Sk': ad_thr = threshold_local(img, bs,method='median', offset=ofs) tmp = 255*(img > ad_thr).astype('uint8') thrconnimg=Image.fromarray(tmp,mode='L') if thrtyp=='Otsu': ret,tmp=cv2.threshold(img, 0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) thrconnimg=Image.fromarray(tmp,mode='L') if thrtyp=='Otsu Loc': radius = bs selem = disk(radius) local_otsu = rank.otsu(img, selem) tmp = 255*(img >= local_otsu).astype('uint8') thrconnimg=Image.fromarray(tmp,mode='L') if thrtyp=='Niblack': ad_thr = threshold_niblack(img, window_size=bs, k=kv) tmp = 255*(img > ad_thr).astype('uint8') thrconnimg=Image.fromarray(tmp,mode='L') if thrtyp=='Sauvola': ad_thr = threshold_sauvola(img, window_size=bs, k=kv, r=rv) tmp = 255*(img > ad_thr).astype('uint8') thrconnimg=Image.fromarray(tmp,mode='L') kernel1 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(4,4)) openimg = Image.fromarray(cv2.morphologyEx(tmp,cv2.MORPH_OPEN,kernel1),mode='L') # openimg2 = Image.fromarray(remove_small_objects((tmp/255).astype('uint8'),mp),mode='L') opimg=255*remove_small_objects((tmp/255).astype('uint8').astype('bool'),mp).astype('uint8') openimg2 = Image.fromarray(opimg,mode='L') # skel=255*skeletonize((opimg/255).astype('uint8')) # skelimg=Image.fromarray(skel,mode='L') if prev=='N': save_tif(stfolder,sfn,fname,openimg2,thrtyp,ext) return openimg2#thrconnimg
def threshold_adaptive(ndarray, method, blocksize=5, offset=0): # Cast to 16-bit #ndarray = convert_array_type(ndarray, 'int16') #Inizialize method_list = ['Mean', 'Gaussian', 'Sauvola', 'Niblack'] if method not in method_list: raise Exception('Mode has to be amond the following:\n' + str(method_list)) blocksize = round_up_to_odd(blocksize) #For 2D images array needs to be reshaped to run properly through next cycle if len(ndarray.shape) < 3: converted_image = [img_as_ubyte(ndarray)] else: converted_image = img_as_ubyte(ndarray) #Cycle through image outputImage = [] for i in range(len(converted_image)): if method == 'Mean': outputImage.append( cv2.adaptiveThreshold(converted_image[i], 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, blocksize, offset)) elif method == 'Gaussian': outputImage.append( cv2.adaptiveThreshold(converted_image[i], 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, blocksize, offset)) elif method == 'Sauvola': outputImage.append(threshold_sauvola(converted_image[i])) elif method == 'Niblack': outputImage.append(threshold_niblack(converted_image[i])) else: raise LookupError('Not a valid method!') #Remove singleton dimension (eg. if image was 2D) outputImage = np.squeeze(np.array(outputImage) > 0).astype(np.uint8) return convert_array_type(outputImage, 'int8')
def thresholding(im, type='Sauvola', window_ratio=0.15, k=0.8): """ Thresholding """ if type == 'Otsu': # Otsu thresholding _, im_thr = cv2.threshold((im*255.0/np.max(im)).astype(np.uint8), 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) elif type == 'Niblack': thresh_niblack = threshold_niblack(im, window_size=int(2*np.floor(np.shape(im)[0]*window_ratio/2)+1), k=k) im_thr = 255*((im < thresh_niblack).astype(np.uint8)) elif type == 'Sauvola': thresh_sauvola = threshold_sauvola(im, window_size=int(2*np.floor(np.shape(im)[0]*window_ratio/2)+1), k=k) im_thr = 255*((im < thresh_sauvola).astype(np.uint8)) return im_thr
def threshold(data, process_param): if process_param["threshold"] == "otsu": thresh = threshold_otsu(data) if process_param["threshold"] == "mean": thresh = threshold_mean(data) if process_param["threshold"] == "minimum": thresh = threshold_minimum(data) if process_param["threshold"] == "yen": thresh = threshold_yen(data) if process_param["threshold"] == "isodata": thresh = threshold_isodata(data) if process_param["threshold"] == "li": thresh = threshold_li(data) if process_param["threshold"] == "local": thresh = threshold_local(data, process_param["local_size"]) if process_param["threshold"] == "local_otsu": selem = disk(process_param["local_size"]) data = data.astype(np.float64) data = data - np.min(data) data = np.uint8(255 * data / np.max(data)) thresh = rank.otsu(data, selem) if process_param["threshold"] == "lg_otsu": selem = disk(process_param["local_size"]) data = data.astype(np.float64) data = data - np.min(data) data = np.uint8(255 * data / np.max(data)) threshl = rank.otsu(data, selem) threshg = threshold_otsu(data) if process_param["threshold"] == "niblack": thresh = threshold_niblack(data, process_param["local_size"]) mask = data > thresh if process_param["threshold"] == "sauvola": thresh = threshold_sauvola(data, process_param["local_size"]) mask = data > thresh if process_param["threshold"] == "lg_otsu": mask1 = data >= threshl mask2 = data > threshg mask = mask1 * mask2 elif process_param["threshold"] == "local_otsu": mask = data >= thresh else: mask = data > thresh labels = label(mask) return (labels)
def filter_show(data): for k in [12, 3088]: img = np.array(data[k]).reshape((28, 28)) image_scharr = scharr(img) image_sobel = sobel(img) image_prewitt = prewitt(img) image_gabor_real, image_gabor_im = gabor(img, frequency=0.65) image_roberts = roberts(img) image_roberts_pos = roberts_pos_diag(img) image_roberts_neg = roberts_neg_diag(img) image_frangi = frangi(img) image_laplace = laplace(img) image_hessian = hessian(img) image_threshold_local_3 = threshold_local(img, 3) image_threshold_local_5 = threshold_local(img, 5) image_threshold_local_7 = threshold_local(img, 7) image_threshold_niblack = threshold_niblack(img, window_size=5, k=0.1) image_threshold_sauvola = threshold_sauvola(img) image_threshold_triangle = img > threshold_triangle(img) fig, axes = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True, figsize=(8, 8)) ax = axes.ravel() ax[0].imshow(img, cmap=plt.cm.gray) ax[0].set_title('Original image') ax[1].imshow(image_threshold_niblack, cmap=plt.cm.gray) ax[1].set_title('Niblack') ax[2].imshow(image_threshold_sauvola, cmap=plt.cm.gray) ax[2].set_title('Sauvola') ax[3].imshow(image_threshold_triangle, cmap=plt.cm.gray) ax[3].set_title('Triangle') for a in ax: a.axis('off') plt.tight_layout() plt.show() plt.close()
def cod16(image): # hint: increase contrast. window_size = 3 # image = cv.imread("sample2.jpg") # image = cv.cvtColor(image, cv.COLOR_RGB2GRAY) # ix = lambda i: cv.cvtColor(i, cv.COLOR_RGB2GRAY) # print(type(image),image.shape) # print(image) image = clahe_demo(image) # must use gray. # print("spliter") # that is f*****g insane. thresh_niblack = ( toReal(threshold_niblack(image, window_size=window_size, k=3)) * 255.0).astype(np.uint8) thresh_sauvola0 = ( toReal(threshold_sauvola(image, window_size=3, k=1.303)) * 255.0).astype(np.uint8) # for full scan? # perfect inverse of the one above thresh_sauvola1 = (toReal( threshold_sauvola(image, window_size=3, k=0.999999999999999999)) * 255.0).astype(np.uint8) # for button detection? # just filter those things out. # thresh_niblack = threshold_niblack(image, window_size=window_size, k=12).astype(np.uint8) # thresh_sauvola0 = threshold_sauvola(image, window_size=3, k=1.103).astype(np.uint8) # for full scan? # # perfect inverse of the one above # thresh_sauvola1 = threshold_sauvola(image, window_size=3, k=1.523).astype(np.uint8) # for button detection? # print(type(thresh_niblack), thresh_niblack.shape) # print(type(thresh_niblack[0][0])) # ndarray. # it just cannot be right. give it up? # the shape can differ. # calcMe(thresh_niblack) # calcMe(thresh_sauvola0) # calcMe(thresh_sauvola1) # cv.imshow("grayimage",thresh_niblack) # cv.waitKey(0) # cv.imshow("thresholdimage", thresh_sauvola0) # cv.waitKey(0) # cv.imshow("thresholdimage", thresh_sauvola1) # cv.waitKey(0) # cv.destroyAllWindows() # return # # use floor function? # # just what the f**k? return thresh_niblack, thresh_sauvola0, thresh_sauvola1
def process(self, input_image): """Converts given image to binary image using Niblack algorithm Arguments: input_image {opencv image} -- input image Returns: opencv image -- Returns binary image where 0 values denotes foreground and 255 background """ thresh_niblack = threshold_niblack(input_image, window_size=self.window_size, k=self.k) output_image = img_as_ubyte(input_image > thresh_niblack) return output_image
def RemoveBackground(img, method, window_size=25, k=0.8): """ Create a binary image separating foreground from background :param img: a numpy array :param method: one of ['otsu', 'niblack', 'sauvola'] :param window_size: size of neighborhood used to define threshold, used in ['niblack', 'sauvola'] :param k: used to tune local threshold, used in ['niblack', 'sauvola'] :return: numpy array, representing a binary image """ image = np.copy(img) if method == 'otsu': threshold = filters.threshold_otsu(img) elif method == 'niblack': threshold = filters.threshold_niblack(img, window_size, k) elif method == 'sauvola': threshold = filters.threshold_sauvola(img) image[image <= threshold] = 0 image[image >= threshold] = 255 return image
def threshold(img, method='otsu', blur_size=None, window_size=25, k=0.8): if blur_size: blur = cv2.GaussianBlur(img, (blur_size, blur_size), 0) else: blur = img if method.strip().lower() == 'otsu': ret, thresh_img = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) if method.strip().lower() == 'sauvola': thresh_values = threshold_sauvola(blur, window_size=window_size) thresh_img = (blur > thresh_values).astype(np.uint8) * 255 if method.strip().lower() == 'niblack': thresh_values = threshold_niblack(blur, window_size=window_size, k=k) thresh_img = (blur > thresh_values).astype(np.uint8) * 255 return thresh_img
def binarisation(image, algorithm_binarisation=None, window_size=25, k=0.8): if algorithm_binarisation == 'otsu': binary = image > threshold_otsu(image) return (binary) elif algorithm_binarisation == 'niblack': thresh_niblack = threshold_niblack(image, window_size=window_size, k=k) binary = image > thresh_niblack return (binary) elif algorithm_binarisation == 'sauvola': thresh_sauvola = threshold_sauvola(image, window_size=window_size) binary = image > thresh_sauvola return (binary) else: print("Algorithme de binarisation inconnu") return (image)
def nick_binarize(img_list): '''Binarize linecut images using two differently sized local threshold kernels Args: img_list: list of grayscale linecut images Returns: results: binarized images in the same order as the input''' results = [] for img in img_list: try: # img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) height = img.shape[0] width = img.shape[1] # Resize the images to 200 pixel height scaling_factor = 100/img.shape[0] new_w = int(scaling_factor*img.shape[1]) new_h = int(scaling_factor*img.shape[0]) # img = cv2.resize(img, (new_w, new_h)) img = np.array(Image.fromarray(img).resize((new_w, new_h), Image.ANTIALIAS)) # First pass thresholding th1 = threshold_niblack(img, 13, 0.00) # Second pass thresholding radius = 101 structured_elem = disk(radius) th2 = rank.otsu(img, structured_elem) # Masking img = (img > th1) | (img > th2) img = img.astype('uint8')*255 img = np.array(Image.fromarray(img).resize((width, height), Image.ANTIALIAS)) results.append(img) except Exception as e: continue return results
def findContoursAndDrawBoundingBox(gray_image): line_upper = []; line_lower = []; line_experiment = [] grouped_rects = [] for k in np.linspace(-1.8, -0.2,5): thresh_niblack = threshold_niblack(gray_image, window_size=25, k=k) binary_niblack = gray_image > thresh_niblack binary_niblack = binary_niblack.astype(np.uint8) * 255 imagex, contours, hierarchy = cv2.findContours(binary_niblack.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) for contour in contours: bdbox = cv2.boundingRect(contour) if (bdbox[3]/float(bdbox[2])>0.5 and bdbox[3]*bdbox[2]>100 and bdbox[3]*bdbox[2]<1300) or (bdbox[3]/float(bdbox[2])>3 and bdbox[3]*bdbox[2]<100): # cv2.rectangle(rgb,(bdbox[0],bdbox[1]),(bdbox[0]+bdbox[2],bdbox[1]+bdbox[3]),(255,0,0),1) line_upper.append([bdbox[0],bdbox[1]]) line_lower.append([bdbox[0]+bdbox[2],bdbox[1]+bdbox[3]]) line_experiment.append([bdbox[0],bdbox[1]]) line_experiment.append([bdbox[0]+bdbox[2],bdbox[1]+bdbox[3]]) # grouped_rects.append(bdbox) rgb = cv2.copyMakeBorder(gray_image,30,30,0,0,cv2.BORDER_REPLICATE) leftyA, rightyA = fitLine_ransac(np.array(line_lower),2) rows,cols = rgb.shape[:2] # rgb = cv2.line(rgb, (cols - 1, rightyA), (0, leftyA), (0, 0, 255), 1,cv2.LINE_AA) leftyB, rightyB = fitLine_ransac(np.array(line_upper),-2) rows,cols = rgb.shape[:2] # rgb = cv2.line(rgb, (cols - 1, rightyB), (0, leftyB), (0,255, 0), 1,cv2.LINE_AA) pts_map1 = np.float32([[cols - 1, rightyA], [0, leftyA],[cols - 1, rightyB], [0, leftyB]]) pts_map2 = np.float32([[136,36],[0,36],[136,0],[0,0]]) mat = cv2.getPerspectiveTransform(pts_map1,pts_map2) image = cv2.warpPerspective(rgb,mat,(136,36)) return image
def binarize(inputfile): image = imread(inputfile, as_grey=True) binary_global = image > threshold_otsu(image) window_size = 25 thresh_niblack = threshold_niblack(image, window_size=window_size, k=0.8) thresh_sauvola = threshold_sauvola(image, window_size=window_size) binary_niblack = image > thresh_niblack binary_sauvola = image > thresh_sauvola # plt.figure(figsize=(8, 7)) # plt.subplot(2, 2, 1) plt.figure(1) plt.imshow(image, cmap=plt.cm.gray) plt.title('Original') plt.axis('off') plt.show() # plt.subplot(2, 2, 2) plt.figure() plt.title('Global Threshold') plt.imshow(binary_global, cmap=plt.cm.gray) plt.axis('off') plt.show() # plt.subplot(2, 2, 3) plt.figure(3) plt.imshow(binary_niblack, cmap=plt.cm.gray) plt.title('Niblack Threshold') plt.axis('off') plt.show() # plt.subplot(2, 2, 4) plt.figure(4) plt.imshow(binary_sauvola, cmap=plt.cm.gray) plt.title('Sauvola Threshold') plt.axis('off') plt.imsave(outputfile, binary_sauvola, cmap=plt.cm.gray) plt.show()
def test_threshold_methods(img): images = {} img_gray = rgb2gray(img) images['grayscale'] = img_gray images['threshold_local_5'] = threshold_local(img_gray, block_size=5) images['threshold_local_11'] = threshold_local(img_gray, block_size=11) th = threshold_multiotsu(img_gray) images['threshold_multiotsu'] = np.digitize(img_gray, bins=th) th = threshold_otsu(img_gray) images['threshold_otsu'] = img_gray >= th th = threshold_li(img_gray) images['threshold_li'] = img_gray >= th th = threshold_yen(img_gray) images['threshold_yen'] = img_gray >= th th = threshold_mean(img_gray) images['threshold_mean'] = img_gray > th th = threshold_niblack(img_gray, window_size=25, k=0.8) images['thresh_niblack'] = img_gray > th th = threshold_sauvola(img_gray, window_size=25) images['threshold_sauvola'] = img_gray > th plot_images(images, 4, 4, cmap='gray')
import matplotlib import matplotlib.pyplot as plt from skimage.data import page from skimage.filters import (threshold_otsu, threshold_niblack, threshold_sauvola) matplotlib.rcParams['font.size'] = 9 image = page() binary_global = image > threshold_otsu(image) window_size = 25 thresh_niblack = threshold_niblack(image, window_size=window_size, k=0.8) thresh_sauvola = threshold_sauvola(image, window_size=window_size) binary_niblack = image > thresh_niblack binary_sauvola = image > thresh_sauvola plt.figure(figsize=(8, 7)) plt.subplot(2, 2, 1) plt.imshow(image, cmap=plt.cm.gray) plt.title('Original') plt.axis('off') plt.subplot(2, 2, 2) plt.title('Global Threshold') plt.imshow(binary_global, cmap=plt.cm.gray) plt.axis('off')