def sliceThreshold(volume, block_size=5): """ convert slice into binary using adaptive local ostu method volume --- 3D volume block_size --- int value """ if type(volume) != np.ndarray: raise TypeError('the input must be numpy array!') x, y, z = volume.shape segImg = np.empty_like(volume) for i in range(z): binary_adaptive = threshold_adaptive(volume[:, :, i], block_size, offset=0) segImg[:, :, i] = binary_adaptive return segImg
def intensity_object_features(im, adaptive_t_radius=51, sample_size=None): """Segment objects based on intensity threshold and compute properties. Parameters ---------- im : 2D np.ndarray of float or uint8. The input image. adaptive_t_radius : int, optional The radius to calculate background with adaptive threshold. sample_size : int, optional Sample this many objects randomly, rather than measuring all objects. Returns ------- f : 1D np.ndarray of float The feature vector. names : list of string The list of feature names. """ tim1 = im > imfilter.threshold_otsu(im) f1, names1 = object_features(tim1, im, sample_size=sample_size) names1 = ['otsu-threshold-' + name for name in names1] tim2 = imfilter.threshold_adaptive(im, adaptive_t_radius) f2, names2 = object_features(tim2, im, sample_size=sample_size) names2 = ['adaptive-threshold-' + name for name in names2] f = np.concatenate([f1, f2]) return f, names1 + names2
def apply(self, matrix): binary = [] if self.func == 'global': value = 0 if self.method == 'otsu': value = threshold_otsu(matrix) if self.method == 'isodata': value = threshold_isodata(matrix) if self.method == 'yen': value = threshold_yen(matrix) if self.method == 'median': value = numpy.median(matrix) if self.method == 'kmeans': aa = numpy.array(matrix).reshape(-1) aa.shape = (aa.shape[0], 1) cc = k_means(aa, 5) ccc = cc[0].reshape(-1) ccc.sort() value = ccc[len(ccc) - 2] binary = matrix > value if self.func == 'adaptive': binary = threshold_adaptive(matrix, 127, self.method) return binary.astype('float')
def make_prediction(): import sys import numpy as np import pandas as pd from skimage.data import imread from skimage.filters import threshold_adaptive from skimage.restoration import denoise_tv_bregman from sklearn.cross_validation import train_test_split from sklearn.grid_search import GridSearchCV from sklearn.neighbors import KNeighborsClassifier from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier from model_design import model_design classifier = model_design() X, IDs = [], range(6284, 12504) for ID in IDs: original = imread('../data/testResized/' + str(ID) +'.Bmp', as_grey=True) denoised = denoise_tv_bregman(original, 3) binarilized = threshold_adaptive(denoised, block_size=13, method='gaussian') feature = binarilized.reshape(1,400)[0] X.append(feature) X = np.array(X) y = classifier.predict(X) result = pd.DataFrame({'Id': IDs, 'Class': y}) result.to_csv('../result/06-09-2015_AdaBoostXTC.csv', sep=',', index=None, columns=['Id', 'Class'])
def segment(self, image): """ """ # image = src[:] if self.use_adaptive_threshold: bs = self.blocksize if not bs % 2: bs += 1 markers = threshold_adaptive(image, bs) # n = markers[:].astype('uint8') n = markers.astype('uint8') # n[markers] = 255 # n[invert(markers)] = 1 # markers = n return n else: markers = zeros_like(image) # print('image',image.max(), image.min()) # print('le', image<self.threshold_low) # print('ge', image>self.threshold_high) markers[image <= self.threshold_low] = 1 markers[image > self.threshold_high] = 255 #elmap = sobel(image, mask=image) elmap = canny(image, sigma=1) wsrc = watershed(elmap, markers, mask=image) return invert(wsrc)
def compute_base_mask(self, params): """Creates the base mask for the base image. Needs the base image, an instance of imageloaderparams and the clip area, which should be already defined by the load_base_image method To create the base mask, two algorithms are available, on based on the threshold_isodata and the other one on the threshold_adaptive functions of the scikit-image.threshold module. """ x0, y0, x1, y1 = self.clip base_mask = np.copy(self.base_image[x0:x1, y0:y1]) if params.mask_algorithm == "Isodata": isodata_threshold = threshold_isodata(base_mask) base_mask = img_as_float(base_mask <= isodata_threshold) elif params.mask_algorithm == "Local Average": # need to invert because threshold_adaptive sets dark parts to 0 base_mask = 1.0 - threshold_adaptive(base_mask, params.mask_blocksize, offset=params.mask_offset) else: print "Not a valid mask algorithm" self.base_mask = 1 - base_mask
def threshold_images(img, method='otsu', thresh_cor=None, thresh=None, fill=False, block_size=10, # only for adaptive **kwargs): if method.lower() == 'otsu': thresh = filters.threshold_otsu(img) if thresh_cor is None: tresh_img = img > thresh else: tresh_img = img > thresh * thresh_cor elif method.lower() == 'adaptive': thresh = filters.threshold_adaptive(img, block_size, **kwargs) if thresh_cor is None: tresh_img = img > thresh else: tresh_img = img > thresh * thresh_cor elif method.lower() == 'manual': if thresh is None: raise NameError( 'when using manual thresholding, supply a threshold') else: raise NameError('Invalid threshold method used') if fill: tresh_img = sp.ndimage.binary_fill_holes(tresh_img) return tresh_img
def mip_plot(x, axis='Z', ax=None, cmap='viridis', do_thresholding=False, block_size=45, offset=20): # Dimension selection if x.ndim >= 4: x = x[:, :, :, 0] # MIP and thresholding axis_int = axis_name_to_int[axis] mip_array = np.max(x, axis=axis_int) if do_thresholding: binary_adaptive = threshold_adaptive(mip_array, method='gaussian', block_size=block_size, offset=offset) mip_array = mip_array * binary_adaptive # Plot if ax is None: fig, ax = plt.subplots(1, 1, figsize=(5, 5)) ax.imshow(mip_array, cmap=cmap) axis_names_plot = [j for i, j in enumerate(axis_names) if i != axis_int] ax.set_xlabel(axis_names_plot[1]) ax.set_ylabel(axis_names_plot[0]) return ax
def adaptive_threshold_mask(frame): """ adaptive thresholding with boolean output """ block_size = 15 frame = filters.threshold_adaptive(grayscale(frame), block_size=block_size) return frame
def adaptive_threshold(frame): """ apply adaptive thresholding. grayscale output. """ block_size = 7 frame = filters.threshold_adaptive(grayscale(frame), block_size=block_size) return frame.astype(np.uint8)*255
def scan(file): image = cv2.imread(file) print image.shape ratio = image.shape[0] / 500.0 orig = image.copy() image = imutils.resize(image, height=500) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray, (5, 5), 0) edged = cv2.Canny(gray, 75, 200) (cnts, _) = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:5] for c in cnts: peri = cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, 0.02 * peri, True) if len(approx) == 4: screenCnt = approx break warped = four_point_transform(orig, screenCnt.reshape(4, 2) * ratio) warped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY) warped = threshold_adaptive(warped, 251, offset=10) warped = warped.astype("uint8") * 255 cv2.imwrite(file, warped)
def define_skeleton(imagem, block_size, offset): binary_adaptive = threshold_adaptive(imagem, block_size, offset=offset) binary_adaptive = invert(binary_adaptive) binary_adaptive = skeletonize(binary_adaptive) return binary_adaptive
def get_symbols(image): dil_eros = bin_search(dilatation_cross_numb, [image], (1, 16), 1.0, "dec") block_size = 50 binary_adaptive_image = erosion(dilation(threshold_adaptive( array(image.convert("L")), block_size, offset=10), square(dil_eros)), square(dil_eros)) all_labels = label(binary_adaptive_image, background = True) objects = find_objects(all_labels) av_width = av_height = 0 symbols = [] for obj in objects: symb = (binary_adaptive_image[obj], (obj[0].start, obj[1].start)) symbols.append(symb) av_height += symb[0].shape[0] av_width += symb[0].shape[1] av_width /= float(len(objects)) av_height /= float(len(objects)) symbols = [symb for symb in symbols if symb[0].shape[0] >= av_height and symb[0].shape[1] >= av_width] return symbols
def adaptive_threshold(image): # In adaptive thresholding, sometimes called local thresholding, # our goal is to statistically examine the pixel intensity values in the neighborhood of a given pixel p. # However, choosing the size of the pixel neighborhood for local thresholding is absolutely crucial. gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(gray, (7, 7), 0) # instead of manually specifying the threshold value, we can use adaptive # thresholding to examine neighborhoods of pixels and adaptively threshold # each neighborbood -- in this example, we'll calculate the mean value # of the neighborhood area of 11 pixels and threshold based on that value; # finally, our constant C is subtracted from the mean calculation (in this # case 4) opencv_thresh = cv2.adaptiveThreshold(blurred, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 25, 15) cv2.imshow("Opencv Thresh", opencv_thresh) # personally, I prefer the scikit-image adaptive thresholding, it just # feels a lot more "Pythonic" skimage_thresh = threshold_adaptive(blurred, 30, offset=5).astype( np.uint8) * 255 skimage_thresh = cv2.bitwise_not(skimage_thresh) cv2.imshow("Scikit image Mean Thresh", skimage_thresh)
def getPaper(edgeMap, gray, image): cnts = cv2.findContours(edgeMap.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = cnts[0] if imutils.is_cv2() else cnts[1] targetCnt = None if len(cnts) > 0: # sort the contours according to their size in # descending order cnts = sorted(cnts, key=cv2.contourArea, reverse=True) for c in cnts: # approximate the contour peri = cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, 0.1 * peri, True) # if our approximated contour has four points, # then we can assume we have found the target if len(approx) == 4: targetCnt = approx break # apply a four point perspective transform to the # paper images to obtain a rectilinear view of the paper # print(type(targetCnt.reshape(4, 2))) warped = four_point_transform(gray, targetCnt.reshape(4, 2)) paper = four_point_transform(gray, targetCnt.reshape(4, 2)) cv2.imshow("ppr", paper) # apply scikit adaptive threshold to image. # this is better than a threshold if there is varied lighting on the paper thresh = img_as_ubyte(threshold_adaptive(warped, 257, offset=10)) return (thresh, paper)
def transform_perspective(image, board): ratio = image.shape[0] / 500.0 warped = transform.four_point_transform(image, board.reshape(4, 2) * ratio) warped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY) warped = threshold_adaptive(warped, 250, offset = 10) warped = warped.astype("uint8") * 255 cv2.imwrite("scanned.png", warped)
def intensity_object_features(im, adaptive_t_radius=51, sample_size=None): """Segment objects based on intensity threshold and compute properties. Parameters ---------- im : 2D np.ndarray of float or uint8. The input image. adaptive_t_radius : int, optional The radius to calculate background with adaptive threshold. sample_size : int, optional Sample this many objects randomly, rather than measuring all objects. Returns ------- f : 1D np.ndarray of float The feature vector. names : list of string The list of feature names. """ tim1 = im > imfilter.threshold_otsu(im) f1, names1 = object_features(tim1, im, sample_size=sample_size) names1 = ['otsu-threshold-' + name for name in names1] tim2 = imfilter.threshold_adaptive(im, adaptive_t_radius) f2, names2 = object_features(tim2, im, sample_size=sample_size) names2 = ['adaptive-threshold-' + name for name in names2] f = np.concatenate([f1, f2]) return f, names1 + names2
def makeMask(filename): # open the image, resize it and turn it to greyscale image = Image.open('thresholdTest/' + filename + '.jpg').convert('L') image = resizeImg(image, 1500) greyscale = np.array(image) # compute the global and adaptive thresholds thresh = threshold_otsu(greyscale) binary = greyscale > thresh binary_adaptive = threshold_adaptive(greyscale, method='mean', block_size=75, offset=10) # turn white space into transparency normal_threshold = toimage(binary).convert("RGBA") adaptive_threshold = toimage(binary_adaptive).convert("RGBA") normal_threshold = addTransparency(normal_threshold) adaptive_threshold = addTransparency(adaptive_threshold) # save the files and overlay then normal_threshold.save('thresholdTest/adaptiveThreshold/' + filename + "_normal_threshold.jpg") adaptive_threshold.save('thresholdTest/adaptiveThreshold/' + filename + "_adaptive_threshold.jpg") adaptive_threshold.paste(normal_threshold, (0, 0), normal_threshold) #adaptive_threshold.show() adaptive_threshold.save('thresholdTest/adaptiveThreshold/' + filename + "_combined_threshold.jpg")
def binarize_images(data): binarized_data = [] for image in data: binary_adaptive = threshold_adaptive(image.reshape((62, 47)), block_size=15) binarized_data.append(binary_adaptive.ravel()) return asfloat(binarized_data)
def compute_base_mask(self, params): """Creates the base mask for the base image. Needs the base image, an instance of imageloaderparams and the clip area, which should be already defined by the load_base_image method To create the base mask, two algorithms are available, on based on the threshold_isodata and the other one on the threshold_adaptive functions of the scikit-image.threshold module. """ x0, y0, x1, y1 = self.clip base_mask = np.copy(self.base_image[x0:x1, y0:y1]) if params.mask_algorithm == "Isodata": isodata_threshold = threshold_isodata(base_mask) base_mask = img_as_float(base_mask <= isodata_threshold) elif params.mask_algorithm == "Local Average": # need to invert because threshold_adaptive sets dark parts to 0 block_size = params.mask_blocksize if block_size % 2 == 0: block_size += 1 base_mask = 1.0 - threshold_adaptive( base_mask, block_size, offset=params.mask_offset) else: print "Not a valid mask algorithm" self.base_mask = 1 - base_mask
def processImage(self, fileBuffer): # tmp_name = uuid.uuid4().__str__() + ".png" try: image = Image.open(fileBuffer) image.thumbnail(self.size) converted = image.convert("L") # converted = ImageEnhance.Contrast(converted).enhance(1.1) # converted = ImageEnhance.Brightness(converted).enhance(1.1) converted = ImageEnhance.Sharpness(converted).enhance(1.4) # image = np.array(converted) image = matplotlib.image.pil_to_array(converted) binary_adaptive = threshold_adaptive(image, 40, offset=10) figsize = [ x / float(self._dpi) for x in (binary_adaptive.shape[1], binary_adaptive.shape[0]) ] fig = Figure(figsize=figsize, dpi=self._dpi, frameon=False) canvas = FigureCanvasAgg(fig) fig.figimage(binary_adaptive) output = StringIO() fig.savefig(output, format='png') output.seek(0) self.outfiles.append(output) except IOError: self.invalidFiles.append(fileBuffer)
def img_to_game_map(paper_img, resized_image, green_img, black_img, red_img, blue_img, pink_img): # convert the paper_img image to grayscale, then threshold it paper_img = cv2.cvtColor(resized_image, cv2.COLOR_BGR2GRAY) paper_img = threshold_adaptive(paper_img, 251, offset=10) paper_img = paper_img.astype("uint8") * 255 nrows = paper_img.shape[0] ncols = paper_img.shape[1] game_map = np.zeros((nrows, ncols)) for i in range(nrows): for j in range(ncols): if (paper_img[i][j] == 255): game_map[i][j] = 1 # background block else: if (green_img[i][j][2] > 3): game_map[i][j] = 12 # points block elif (black_img[i][j][2] == 0): game_map[i][j] = 2 # wall block elif (red_img[i][j][2] > 3): game_map[i][j] = 9 # lava block elif (blue_img[i][j][2] > 3): game_map[i][j] = 8 # endpoint block elif (pink_img[i][j][2] > 5): game_map[i][j] = 5 # bouncy block else: # if something there but none of the above colors default to wall block (black) game_map[i][j] = 2 return game_map
def mask_image(im, thresh=None, min_size=15): """ Create a binary mask to segment nuclei using adaptive threshold. Useful to find nuclei of varying intensities. Remove small objects, fill holes and perform binary opening (erosion followed by a dilation. Opening can remove small bright spots (i.e. “salt”) and connect small dark cracks. This tends to “open” up (dark) gaps between (bright) features.) Arguments --------- im: array_like input image thresh: array_like, optional thresholded image min_size: float or int minimum size of objects to retain Returns --------- im_thresh: array_like thresholded binary image """ if not thresh: im_thresh = threshold_adaptive(im, 15) im_thresh = skimage.morphology.remove_small_objects(im_thresh, min_size=min_size) im_thresh = ndimage.morphology.binary_fill_holes(im_thresh, morphology.disk(1.8)) im_thresh = morphology.binary_opening(im_thresh) return im_thresh
def processImage(self, fileBuffer): # tmp_name = uuid.uuid4().__str__() + ".png" try: image = Image.open(fileBuffer) image.thumbnail(self.size) converted = image.convert("L") # converted = ImageEnhance.Contrast(converted).enhance(1.1) # converted = ImageEnhance.Brightness(converted).enhance(1.1) converted = ImageEnhance.Sharpness(converted).enhance(1.4) # image = np.array(converted) image = matplotlib.image.pil_to_array(converted) binary_adaptive = threshold_adaptive(image, 40, offset=10) figsize = [x / float(self._dpi) for x in (binary_adaptive.shape[1], binary_adaptive.shape[0])] fig = Figure(figsize=figsize, dpi=self._dpi, frameon=False) canvas = FigureCanvasAgg(fig) fig.figimage(binary_adaptive) output = StringIO() fig.savefig(output, format='png') output.seek(0) self.outfiles.append(output) except IOError: self.invalidFiles.append(fileBuffer)
def lt(detector,method,input=0,refLam=0,N=200): #N=smoothingLength #100 dSmooth=signal.convolve(detector, np.ones((N,))/N, mode='valid') #now smoothing is done outside #dSmooth=signal.convolve(dSmooth, np.ones((N,))/N, mode='valid') #dSmooth2=running_mean(detector,N) dt=1e-5 #dSmooth2=highpass_filter(detector,1/dt,1/(dt*50),2/(dt*50),1001) # dSmooth = generic_filter(detector, np.std, size=N) ##std filter # blur=signal.convolve(detector, np.ones((N,))/N, mode='valid') # blur2=signal.convolve(np.square(detector), np.ones((N,))/N, mode='valid') # dSmooth=np.sqrt(blur2-np.square(blur)) # pl.figure(10) # pl.plot(detector,'k') # pl.plot(dSmooth,'-r') # pl.plot(dSmooth2,'-b') # pl.show() ## Laminar/Turbulent Discrimination if method=='otsuloc': ### Otsu thresh_otsu= filters.threshold_otsu(np.concatenate((dSmooth,refLam),axis=None)) lt_otsu=np.where(dSmooth>thresh_otsu, 1, 0) # Laminar_Turbulent, Ostu lamtu = lt_otsu print("Otsu Threshhold={:.2e}".format(thresh_otsu)) #pl.plot(time[int(N/2):int(-N/2+1)],lt_otsu,'-r',label="LT") elif method=='adaptive': # ### Adaptive block_size = 5001 print(np.tile(dSmooth,(2,1)).shape) lt_adaptive = filters.threshold_adaptive(np.tile(dSmooth,(2,1)), block_size, offset=100)*1 lamtu = lt_adaptive[0,:] print(lt_adaptive[0,:].shape) #pl.plot(time[int(N/2):int(-N/2+1)],lt,'-k',label="LT") elif method=='percentageMax': ### Arbitrary fraction of Max D C = input lt_cmax=np.where(dSmooth>C*np.max(dSmooth),1,0)#0.01*24473540.92065062,1,0)#>0.01*269112747.3345178,1,0) ##6419964748.39, 1, 0) # Laminar_Turbulent, C*max(D) lamtu = lt_cmax #pl.plot(time[int(N/2):int(-N/2+1)],lt_cmax,'-b',label="LT") elif method=='thresh': thresh = input ### threshhold, can be c*Max(D) or otsu global #lt_cmax=np.where(DSmooth>C*np.max(DSmooth), 1, 0) # Laminar_Turbulent, C*max(D) lt_cmax=np.where(dSmooth>thresh,1,0)#0.01*24473540.92065062,1,0)#>0.01*269112747.3345178,1,0) ##6419964748.39, 1, 0) # Laminar_Turbulent, C*max(D) lamtu = lt_cmax #pl.plot(time[int(N/2):int(-N/2+1)],lt_cmax,'-b',label="LT") elif method=='meanshift': #not complete, dont use bw=estimate_bandwidth(np.tile(dSmooth,(2,1))) print(bw) if bw<10: bw=10 clustering = MeanShift(bandwidth=1000).fit(np.tile(dSmooth,(2,1))) lamtu=clustering.labels_ return lamtu
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.")
def text_segments(img, min_h=20, max_h=50): gray_scale_img = rgb2grayscale(img) binarized_adaptive_img = threshold_adaptive(gray_scale_img, block_size=40, offset=20) dilated = dilation(~binarized_adaptive_img, rectangle(1, 15)) for segment in extract_segments(dilated.copy()): if min_h < height(segment) < max_h: yield segment
def showthres(iteration): data = pmi2array.readdatas(int(np.floor(iteration / 3))) ##adaptive threasholding for i in xrange(iteration): thres = threshold_adaptive(data[i], 33, offset=-100) op = opening(thres, disk(1)) plt.figure(i) pmi2array.showfound(data[i], op)
def threshold_mask(img, sz, t): img_rescaled = ((img - img.min(axis=(0, 1))) / (img.max(axis=(0, 1)) - img.min(axis=(0, 1))) - 0.5) * 2 grey = rgb2grey(img_rescaled) grey_resized = resize(grey, sz, preserve_range=True) grad = np.sqrt(sobel_h(grey_resized)**2 + sobel_v(grey_resized)**2) thr = threshold_adaptive(grad, t, method='mean') return thr.astype(int)[None, :, :, None]
def segmentation(image): global_thresh = threshold_otsu(image) binary_global = image > global_thresh block_size = 255 binary_adaptive = threshold_adaptive(image, block_size, offset=5) return binary_global, binary_adaptive
def Filtro12(matrix_imagem): #mediana,and treshold_adptive matrix_imagem = Filtro11(matrix_imagem) mat_empty = np.zeros_like(matrix_imagem) for i in xrange(matrix_imagem.shape[0]): mat_empty[i] = filters.threshold_adaptive(matrix_imagem[i], 3) return mat_empty
def otsu_adap(data, block_size, offset): from skimage.filters import threshold_adaptive mask = data for iz in range(data.shape[2]): mask[:, :, iz] = threshold_adaptive(data[:, :, iz], block_size, offset) # mask[:, :, iz] = threshold_otsu(data[:, :, iz], 5) return mask
def otsu_adap(data, block_size, offset): from skimage.filters import threshold_adaptive mask = data for iz in range(data.shape[2]): mask[:, :, iz] = threshold_adaptive(data[:, :, iz], block_size, offset) # mask[:, :, iz] = threshold_otsu(data[:, :, iz], 5) return mask
def get_nuclei(img, opening_radius=6, block_size=80, threshold_offset=0): s = Sample(DOWNSAMPLE) binary = threshold_adaptive(s.downsample(img), int(block_size / s.rate), offset=threshold_offset) filled = fill_holes(binary) opened = opening(filled, selem=disk(opening_radius / s.rate)) nuclei = apply_watershed(opened) nuclei = s.upsample(nuclei) return img_as_uint(nuclei)
def cut(image): V = cv2.split(cv2.cvtColor(image, cv2.COLOR_BGR2HSV))[2] thresh = threshold_adaptive(V, 29, offset=15).astype("uint8") * 255 thresh = cv2.bitwise_not(thresh) # perform a connected components analysis and initialize the mask to store the locations # of the character candidates labels = measure.label(thresh, neighbors=8, background=0) boxes = [] # loop over the unique components for label in np.unique(labels): # if this is the background label, ignore it if label == 0: continue # otherwise, construct the label mask to display only connected components for the # current label, then find contours in the label mask labelMask = np.zeros(thresh.shape, dtype="uint8") labelMask[labels == label] = 255 (_, cnts, _) = cv2.findContours(labelMask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # ensure at least one contour was found in the mask if len(cnts) > 0: # grab the largest contour which corresponds to the component in the mask, then # grab the bounding box for the contour c = max(cnts, key=cv2.contourArea) (boxX, boxY, boxW, boxH) = cv2.boundingRect(c) # compute the aspect ratio, solidity, and height ratio for the component aspectRatio = boxW / float(boxH) solidity = cv2.contourArea(c) / float(boxW * boxH) heightRatio = boxH / float(thresh.shape[0]) # determine if the aspect ratio, solidity, and height of the contour pass # the rules tests keepAspectRatio = aspectRatio < 1.0 keepSolidity = solidity > 0.15 keepHeight = heightRatio > 0.4 and heightRatio < 0.95 # check to see if the component passes all the tests if keepAspectRatio and keepSolidity and keepHeight: # compute the convex hull of the contour and draw it on the character # candidates mask # hull = cv2.convexHull(c) # cv2.drawContours(charCandidates, [hull], -1, 255, -1) # dX = min(35, 35 - boxW) // 2 boxX -= dX boxW += (dX * 2) boxes.append((boxX, boxY, boxX + boxW, boxY + boxH)) # sort the bounding boxes from left to right boxes = sorted(boxes, key=lambda b: b[0]) return boxes, thresh
def fixedThresholding(img, threshold): #func = lambda x: 0 if x>threshold else 255 def func(x): if x > threshold: return 0 else: return 255 return filters.threshold_adaptive(img, 1, 'generic', param=func)
def binarisation1(src_image): if len(src_image.shape) == 3: image = (src_image.sum(axis=2) / 3).astype('ubyte') else: image = src_image block_size = 35 binary = threshold_adaptive(image, block_size, offset=20) binary = binary.astype('ubyte') return binary
def predict_data(): X, IDs = [], range(6284, 12504) for ID in IDs: original = imread('../data/testResized/' + str(ID) +'.Bmp', as_grey=True) denoised = denoise_tv_bregman(original, 3) binarilized = threshold_adaptive(denoised, block_size=13, method='gaussian') feature = binarilized.reshape(1,400)[0] X.append(feature) X = np.array(X) return X
def image_to_scan_bird_style_view(image, screenCnt, ratio): # apply the four point transform to obtain a top-down # view of the original image warped = four_point_transform(image, screenCnt.reshape(4, 2) * ratio) # convert the warped image to grayscale, then threshold it # to give it that 'black and white' paper effect warped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY) warped = threshold_adaptive(warped, 250, offset=10) warped = warped.astype("uint8") * 255 return warped
def binarisation_(src_image): if len(src_image.shape) == 3: image = (src_image.sum(axis=2) / 3).astype('ubyte') else: image = src_image block_size = 35 binary = threshold_adaptive(image, block_size, offset=20) binary = binary.astype('ubyte') #im = (binary * 255).astype('ubyte') return binary
def adaptivethresh2blocks(img, holder, ADAPTIVEBLOCK=21, DEBRISAREA=50, MAXSIZE=1000, OPENING=2, FILTERSIZE=1, SHRINK=0, REGWSHED=10): img = gaussian_filter(img, FILTERSIZE) bw = skifilter.threshold_adaptive(img, ADAPTIVEBLOCK, 'gaussian') bw2 = skifilter.threshold_adaptive(img, img.shape[0] / 4, 'gaussian') bw = bw * bw2 bw = sizefilterandopen(bw, DEBRISAREA, MAXSIZE, OPENING) if SHRINK > 0: bw = binary_erosion(bw, np.ones((SHRINK, SHRINK))) label = devide_and_label_objects(bw, REGWSHED) label = sizefilter_for_label(label, DEBRISAREA, MAXSIZE, OPENING) label = skilabel(clear_border(label, buffer_size=2)) return label
def adaptive_thresholding(self): #block_size = 55 image_gray = color.rgb2gray(self._image) binary_adaptive = filters.threshold_adaptive( image_gray, block_size=self._block_size, method=self._method, offset=self._offset) return (255 * binary_adaptive.astype(np.uint8))
def process_image(fname): image = cv2.imread(fname) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) fnames = [] # extract the Value component from the HSV color space and apply adaptive thresholding # to reveal the characters on the license plate V = cv2.split(cv2.cvtColor(image, cv2.COLOR_BGR2HSV))[2] thresh = threshold_adaptive(V, 30, offset=15).astype("uint8") * 255 thresh = cv2.bitwise_not(thresh) labels = measure.label(thresh, neighbors=8, background=0) mask = np.zeros(thresh.shape, dtype="uint8") # loop over the unique components for (i, label) in enumerate(np.unique(labels)): # if this is the background label, ignore it if label == -1: print("[INFO] label: -1 (background)") continue # otherwise, construct the label mask to display only connected components for # the current label # print("[INFO] label: {} (foreground)".format(i)) labelMask = np.zeros(thresh.shape, dtype="uint8") labelMask[labels == label] = 255 numPixels = cv2.countNonZero(labelMask) # if the number of pixels in the component is sufficiently large, add it to our # mask of "large" blobs if numPixels > 300 and numPixels < 1500: mask = cv2.add(mask, labelMask) # show the label mask fn = os.path.join('images', 'labels', os.path.splitext(os.path.basename(fname))[0], 'label_%.3d.jpg' % i) fnames.append(fn) fn = os.path.join(out_path, fn) if not os.path.exists(os.path.dirname(fn)): os.makedirs(os.path.dirname(fn)) cv2.imwrite(fn, imutils.resize(labelMask, width=160)) # show the large components in the image fn = os.path.join('images', 'labels', os.path.basename(fname)) fnames.insert(0, fn) cv2.imwrite(os.path.join(out_path, fn), imutils.resize(mask, width=160)) print '%d files' % len(fnames) json.dump({ 'files': fnames, 'title': os.path.splitext(os.path.basename(__file__))[0], }, file(os.path.join(out_path, 'frames.json'), 'w'), indent=2)
def intensity_object_features(im, threshold=None, adaptive_t_radius=51, sample_size=None, random_seed=None): """Segment objects based on intensity threshold and compute properties. Parameters ---------- im : 2D np.ndarray of float or uint8. The input image. threshold : float, optional A threshold for the image to determine objects: connected pixels above this threshold will be considered objects. If ``None`` (default), the threshold will be automatically determined with both Otsu's method and a locally adaptive threshold. adaptive_t_radius : int, optional The radius to calculate background with adaptive threshold. sample_size : int, optional Sample this many objects randomly, rather than measuring all objects. random_seed: int, or numpy RandomState instance, optional An optional random number generator or seed from which to draw samples. Returns ------- f : 1D np.ndarray of float The feature vector. names : list of string The list of feature names. """ if threshold is None: tim1 = im > imfilter.threshold_otsu(im) f1, names1 = object_features(tim1, im, sample_size=sample_size, random_seed=random_seed) names1 = ['otsu-threshold-' + name for name in names1] tim2 = imfilter.threshold_adaptive(im, adaptive_t_radius) f2, names2 = object_features(tim2, im, sample_size=sample_size, random_seed=random_seed) names2 = ['adaptive-threshold-' + name for name in names2] f = np.concatenate([f1, f2]) names = names1 + names2 else: tim = im > threshold f, names = object_features(tim, im, sample_size=sample_size, random_seed=random_seed) return f, names
def adaptivethreshold(self, image): '''Uses an adaptive threshold to change image to binary. This is done using the Adaptive Thresholding technique, begins by using Gaussian filtering to remove noise, follows by creating a binary image with Otsu's Method. Reference: https://en.wikipedia.org/wiki/Otsus_method''' # Image is thresholded, inverted, dilated, and has holes filled. thresh = threshold_adaptive(image, 41, offset=10) thresh = np.invert(thresh) thresh = ndimage.grey_dilation(thresh, size=(2,2)) return ndimage.binary_fill_holes(thresh)
def preprocess_algae(img): # Crop the pictures as for raw images. # Apply thresholds img = filters.threshold_adaptive(img,25) threshold = 0.3 idx = img > img.max() * threshold idx2 = img < img.max() * threshold img[idx] = 255 img[idx2] = 0 return util.img_as_int(img)
def feature_vector_from_rgb(image, sample_size=None): """Compute a feature vector from the composite images. The channels are assumed to be in the following order: - Red: MCF-7 - Green: cytoplasm GFP - Blue: DAPI/Hoechst Parameters ---------- im : array, shape (M, N, 3) The input image. sample_size : int, optional For features based on quantiles, sample this many objects rather than computing full distribution. This can considerably speed up computation with little cost to feature accuracy. Returns ------- fs : 1D array of float The features of the image. names : list of string The feature names. """ all_fs, all_names = [], [] ims = np.rollaxis(image[..., :3], -1, 0) # toss out alpha chan if present mcf, cells, nuclei = ims prefixes = ['mcf', 'cells', 'nuclei'] for im, prefix in zip(ims, prefixes): fs, names = features.intensity_object_features(im, sample_size=sample_size) names = [prefix + '-' + name for name in names] all_fs.append(fs) all_names.extend(names) nuclei_mean = nd.label(nuclei > np.mean(nuclei))[0] fs, names = features.nearest_neighbors(nuclei_mean) all_fs.append(fs) all_names.extend(['nuclei-' + name for name in names]) mcf_mean = nd.label(mcf)[0] fs, names = features.fraction_positive(nuclei_mean, mcf_mean, positive_name='mcf') all_fs.append(fs) all_names.extend(names) cells_t_otsu = cells > threshold_otsu(cells) cells_t_adapt = threshold_adaptive(cells, 51) fs, names = features.nuclei_per_cell_histogram(nuclei_mean, cells_t_otsu) all_fs.append(fs) all_names.extend(['otsu-' + name for name in names]) fs, names = features.nuclei_per_cell_histogram(nuclei_mean, cells_t_adapt) all_fs.append(fs) all_names.extend(['adapt-' + name for name in names]) return np.concatenate(all_fs), all_names
def preprocess(): labels = pd.read_csv('../data/trainLabels.csv', sep=',') X, y = [], np.array(labels.Class) for ID in labels.ID: original = imread('../data/trainResized/' + str(ID) +'.Bmp', as_grey=True) denoised = denoise_tv_bregman(original, 3) binarilized = threshold_adaptive(denoised, block_size=13, method='gaussian') feature = binarilized.reshape(1,400)[0] X.append(feature) X = np.array(X) return X, y
def preprocessImages(self, rootDir, subdir, srcFile): rootfilename, fileType = srcFile.rsplit(".", 1) for subdir, dirs, files in os.walk(rootDir + "/gsPdfs/" + rootfilename + "-imgs"): for src in files: if(".DS_Store" in src): continue filename, fileType = src.rsplit(".", 1) print("Processing image") image = Image.open(subdir + "/" + src).convert('L') image = np.asarray(image) block_size = 7 binary_adaptive = threshold_adaptive(image, block_size, method='gaussian', offset=-35, param=37)
def feature_vector_from_rgb(image, sample_size=None): """Compute a feature vector from the composite images. The channels are assumed to be in the following order: - Red: MCF-7 - Green: cytoplasm GFP - Blue: DAPI/Hoechst Parameters ---------- im : array, shape (M, N, 3) The input image. sample_size : int, optional For features based on quantiles, sample this many objects rather than computing full distribution. This can considerably speed up computation with little cost to feature accuracy. Returns ------- fs : 1D array of float The features of the image. names : list of string The feature names. """ all_fs, all_names = [], [] ims = np.rollaxis(image[..., :3], -1, 0) # toss out alpha chan if present mcf, cells, nuclei = ims prefixes = ['mcf', 'cells', 'nuclei'] for im, prefix in zip(ims, prefixes): fs, names = features.intensity_object_features(im, sample_size=sample_size) names = [prefix + '-' + name for name in names] all_fs.append(fs) all_names.extend(names) nuclei_mean = nd.label(nuclei > np.mean(nuclei))[0] fs, names = features.nearest_neighbors(nuclei_mean) all_fs.append(fs) all_names.extend(['nuclei-' + name for name in names]) mcf_mean = nd.label(mcf)[0] fs, names = features.fraction_positive(nuclei_mean, mcf_mean, positive_name='mcf') all_fs.append(fs) all_names.extend(names) cells_t_otsu = cells > threshold_otsu(cells) cells_t_adapt = threshold_adaptive(cells, 51) fs, names = features.nuclei_per_cell_histogram(nuclei_mean, cells_t_otsu) all_fs.append(fs) all_names.extend(['otsu-' + name for name in names]) fs, names = features.nuclei_per_cell_histogram(nuclei_mean, cells_t_adapt) all_fs.append(fs) all_names.extend(['adapt-' + name for name in names]) return np.concatenate(all_fs), all_names
def binarisation(src_image): if len(src_image.shape) == 3: image = (src_image.sum(axis=2) / 3).astype("ubyte") else: image = src_image thresh = threshold_otsu(image) binary = (image > thresh).astype("ubyte") binary1 = 1 - binary im = 255 - np.multiply(255 - image, binary1) block_size = 35 binary = threshold_adaptive(image, block_size, offset=20) binary = binary.astype("ubyte") return binary
def preprocess_algae_fill(img): # Crop the pictures as for raw images. # Apply thresholds img = filters.threshold_adaptive(img,25) threshold = 0.3 idx = img > img.max() * threshold idx2 = img < img.max() * threshold img[idx] = 255 img[idx2] = 0 img = ndimage.binary_erosion(img) img = ndimage.binary_closing(img) return util.img_as_int(img)
def threshold(): otsu = threshold_adaptive(roiArr, block_size=blockSize, method=threshMethod, offset=offset, mode=threshMode) otsuArr = roiArr >= otsu otsuArr = otsuArr.astype('float64') contours = makeContour(otsuArr) for c in contours: c = c.astype(int) otsuArr[c[:, 0], c[:, 1]] = 3 win.ui.contourImage.setImage(otsuArr) win.ui.contourPlot.autoRange() return contours
def __init__(self, imgpath, is_camera=False): if is_camera: self.img = cv2.imread(imgpath) self.img = cv2.resize(self.img.copy(), (int(.95*self.img.shape[1]), int(.95*self.img.shape[0])), interpolation = cv2.INTER_CUBIC) self.imggray_original = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(self.imggray_original, (5, 5), 0) edged = cv2.Canny(gray, 75, 200) cv2.imshow("test", cv2.resize(edged.copy(), (int(.5*self.img.shape[1]), int(.5*self.img.shape[0])), interpolation = cv2.INTER_CUBIC)) cv2.waitKey(0) img, contours, heir = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) contours = sorted(contours, key=cv2.contourArea, reverse=True) # loop over the contours for i, contour in enumerate(contours): # approximate the contour peri = cv2.arcLength(contour, True) approx = cv2.approxPolyDP(contour, 0.05 * peri, True) # if our approximated contour has four points, then we # can assume that we have found our screen if len(approx) == 4: # if i == 0: screenCnt = approx self.img = four_point_transform(self.img.copy(), screenCnt.reshape(4, 2)) self.imggray_original = four_point_transform(gray, screenCnt.reshape(4, 2)) self.imggray_original = threshold_adaptive(self.imggray_original, 251, offset=10) self.imggray_original = self.imggray_original.astype("uint8") * 255 self.height, self.width, self.channels = self.img.shape cv2.imshow("test", cv2.resize(self.imggray_original, (int(.5 * self.img.shape[1]), int(.5 * self.img.shape[0])), interpolation=cv2.INTER_CUBIC)) cv2.waitKey(0) self.img_pil_gray = Image.fromarray(self.imggray_original) self.imgpath = imgpath self.window_height = int(.01 * self.height) self.window_width = int(.01 * self.width) break else: self.img = cv2.imread(imgpath) self.imggray_original = cv2.cvtColor(self.img.copy(), cv2.COLOR_BGR2GRAY) self.img_pil_gray = Image.fromarray(self.imggray_original) self.imgpath = imgpath self.height, self.width, self.channels = self.img.shape self.window_height = int(.01 * self.height) self.window_width = int(.01 * self.width)
def analyze_image(): global sin_par, dipole, multiple, contours # Change to the gray image img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Adaptive Thresholding block_size = 201 img_binary = threshold_adaptive(img_gray, block_size, offset=7) img_binary = img_binary.astype(dtype='uint8')*255 # Remove the salt and pepper noise img_binary = cv2.medianBlur(img_binary,7) # Fill the hole img_binary = 255-img_binary # Change the white/black for filling the hole seed = np.copy(img_binary) seed[1:-1, 1:-1] = img_binary.max() mask = img_binary filled = reconstruction(seed, mask, method='erosion') filled = filled.astype(dtype = 'uint8') # Find the contours # For terminal use # image, contours, hierarchy = cv2.findContours(filled, # cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) # For Anaconda use hierarchy, contours, hierarchy = cv2.findContours(filled, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) # Calculate the area (= len) of each contour area = np.zeros(len(contours)) area_contour = np.zeros(len(contours)) for kk in range(0,len(contours)): area[kk] = len(contours[kk]) area_contour[kk] = cv2.contourArea(contours[kk]) single = np.where((area_contour>200)&(area_contour<=624))[0] dipole = np.where((area_contour>624)&(area_contour<=936))[0] multiple = np.where(area_contour>936)[0] # Analyze the single particle sin_par = analyze_single(single,filled) # Draw the contours refreshFigure_contours(img,sin_par,dipole,multiple,contours)
def threshold(): for imagePath in glob.glob("./test_img3_bi/*.*"): imagePath.encode('utf-8') imagename = imagePath[imagePath.rfind("/") + 1:] img = cv2.imread(imagePath, 0) binary_adaptive = threshold_adaptive(img, 40, offset=10) arrary = np.asarray(binary_adaptive, dtype="int") for i in range(len(arrary)): for j in range(len(arrary[0])): if arrary[i][j] == 1: arrary[i][j] = 255 else: arrary[i][j] = 0 # print arrary cv2.imwrite('./test_img3_bi/'+imagename, arrary)
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.")
def main(): inputArgs = ap.ArgumentParser() inputArgs.add_argument("-i", "--image", required = True, help = "Path to the image to be scanned") args = vars(inputArgs.parse_args()) image = cv2.imread(args["image"]) ratio = image.shape[0] / 500.0 original = image.copy() image = hf.resize(image, height = 500) # convert the image to grayscale, blur it, and find edges gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray, (5, 5), 0) edged = cv2.Canny(gray, 75, 200) print "Found edges with Edge Detection" # find the contours in the edged image (corners) (_, contours, _) = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) contours = sorted(contours, key = cv2.contourArea, reverse = True)[:5] for c in contours: # approximate the contour perimeter = cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, 0.02 * perimeter, True) if len(approx) == 4: screenCnt = approx break print "Found contours of paper" # apply the four point transform to obtain a top-down view warped = hf.four_point_transform(original, screenCnt.reshape(4, 2) * ratio) # make the image black and white warped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY) warped = threshold_adaptive(warped, 250, offset = 10) warped = warped.astype("uint8") * 255 print "Applying perspective transform" cv2.imshow("PyScan", hf.resize(warped, height = 650)) cv2.imwrite('result.jpg', warped) print "Saving image as result.jpg" cv2.waitKey(0)