我们从Python开源项目中,提取了以下38个代码示例,用于说明如何使用cv2.ADAPTIVE_THRESH_GAUSSIAN_C。
def execute_Threshold(proxy,obj): try: img=obj.sourceObject.Proxy.img.copy() except: img=cv2.imread(__dir__+'/icons/freek.png') # img = cv2.imread('dave.jpg',0) ?? img = cv2.medianBlur(img,5) img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) if obj.globalThresholding: ret,th1 = cv2.threshold(img,obj.param1,obj.param2,cv2.THRESH_BINARY) obj.Proxy.img = cv2.cvtColor(th1, cv2.COLOR_GRAY2RGB) if obj.adaptiveMeanTresholding: th2 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,\ cv2.THRESH_BINARY,11,2) obj.Proxy.img = cv2.cvtColor(th2, cv2.COLOR_GRAY2RGB) if obj.adaptiveGaussianThresholding: th3 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\ cv2.THRESH_BINARY,17,2) obj.Proxy.img = cv2.cvtColor(th3, cv2.COLOR_GRAY2RGB)
def find_bibs(image): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY); binary = cv2.GaussianBlur(gray,(5,5),0) ret,binary = cv2.threshold(binary, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU); #binary = cv2.adaptiveThreshold(binary, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2) #ret,binary = cv2.threshold(binary, 190, 255, cv2.THRESH_BINARY); #lapl = cv2.Laplacian(image,cv2.CV_64F) #gray = cv2.cvtColor(lapl, cv2.COLOR_BGR2GRAY); #blurred = cv2.GaussianBlur(lapl,(5,5),0) #ret,binary = cv2.threshold(blurred, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU); #cv2.imwrite("lapl.jpg", lapl) edges = cv2.Canny(image,175,200) cv2.imwrite("edges.jpg", edges) binary = edges cv2.imwrite("binary.jpg", binary) contours,hierarchy = find_contours(binary) return get_rectangles(contours)
def threshold(im_gray, method): ''' ??????????thresholding??????????? ??????thresholding????????OpenCV?? ''' if method == 'fixed': threshed_im = cv2.threshold(im_gray, 128, 255, cv2.THRESH_BINARY) elif method == 'mean': threshed_im = cv2.adaptiveThreshold(im_gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 15, -22) elif method == 'gaussian': threshed_im = cv2.adaptiveThreshold(im_gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 5, 7) else: return None return threshed_im
def adaptive_threshold(image, above_thresh_assigned=255, kind='mean', cell_size=35, c_param=17, thresh_style=cv.THRESH_BINARY_INV): ''' :param kind: specify adaptive method, whether 'mean' or 'gaussian'. :param cell_size: n for the region size (n x n). :param c_param: subtraction constant. :return: a binary version of the input image. ''' if kind == 'mean': method = cv.ADAPTIVE_THRESH_MEAN_C elif kind == 'gaussian': method = cv.ADAPTIVE_THRESH_GAUSSIAN_C else: raise ValueError('Unknown adaptive threshold method.') return cv.adaptiveThreshold(image, above_thresh_assigned, method, thresh_style, cell_size, c_param)
def find_bib(image): width, height, depth = image.shape gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY); #gray = cv2.equalizeHist(gray) blurred = cv2.GaussianBlur(gray,(5,5),0) debug_output("find_bib_blurred", blurred) #binary = cv2.adaptiveThreshold(blurred, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, blockSize=25, C=0); ret,binary = cv2.threshold(blurred, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU); #ret,binary = cv2.threshold(blurred, 170, 255, cv2.THRESH_BINARY); debug_output("find_bib_binary", binary) threshold_contours,hierarchy = find_contours(binary) debug_output("find_bib_threshold", binary) edges = cv2.Canny(gray,175,200, 3) edge_contours,hierarchy = find_contours(edges) debug_output("find_bib_edges", edges) contours = threshold_contours + edge_contours debug_output_contours("find_bib_threshold_contours", image, contours) rectangles = get_rectangles(contours) debug_output_contours("find_bib_rectangles", image, rectangles) potential_bibs = [rect for rect in rectangles if is_potential_bib(rect, width*height)] debug_output_contours("find_bib_potential_bibs", image, potential_bibs) ideal_aspect_ratio = 1.0 potential_bibs = sorted(potential_bibs, key = lambda bib: abs(aspect_ratio(bib) - ideal_aspect_ratio)) return potential_bibs[0] if len(potential_bibs) > 0 else np.array([[(0,0)],[(0,0)],[(0,0)],[(0,0)]]) # # Checks that the size and aspect ratio of the contour is appropriate for a bib. #
def thresholding(img_grey): """ This functions creates binary images using thresholding :param img_grey: greyscale image :return: binary image """ # # Adaptive Gaussian # img_binary = cv.adaptiveThreshold(img_grey, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 11, 2) # Otsu's thresholding after Gaussian filtering blur = cv.GaussianBlur(img_grey, (5, 5), 0) ret3, img_binary = cv.threshold(blur, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU) # invert black = 255 ret, thresh1 = cv.threshold(img_binary, 127, 255, cv.THRESH_BINARY_INV) return thresh1
def thresholding(img_grey): """ This functions creates binary images using thresholding :param img_grey: greyscale image :return: binary image """ # # Global # ret1, thresh1 = cv.threshold(img_grey, 127, 255, cv.THRESH_BINARY_INV) # show_img(thresh1) # # # Adaptive Mean # img_binary = cv.adaptiveThreshold(img_grey, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 11, 2) # ret2, thresh2 = cv.threshold(img_binary, 127, 255, cv.THRESH_BINARY_INV) # show_img(thresh2) # # # Adaptive Gaussian # img_binary = cv.adaptiveThreshold(img_grey, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 11, 2) # ret3, thresh3 = cv.threshold(img_binary, 127, 255, cv.THRESH_BINARY_INV) # show_img(thresh3) # Otsu's thresholding after Gaussian filtering blur = cv.GaussianBlur(img_grey, (5, 5), 0) ret4, img_otsu = cv.threshold(blur, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU) ret4, thresh4 = cv.threshold(img_otsu, 127, 255, cv.THRESH_BINARY_INV) # show_img(thresh4) return thresh4
def run(self, ips, snap, img, para = None): med = cv2.ADAPTIVE_THRESH_MEAN_C if para['med']=='mean' else cv2.ADAPTIVE_THRESH_GAUSSIAN_C mtype = cv2.THRESH_BINARY_INV if para['inv'] else cv2.THRESH_BINARY cv2.adaptiveThreshold(snap, para['max'], med, para['inv'], para['size'], para['offset'], dst=img)
def get_contour(self, arg_frame, arg_export_index, arg_export_path, arg_export_filename, arg_binaryMethod): # Otsu's thresholding after Gaussian filtering tmp = cv2.cvtColor(arg_frame, cv2.COLOR_RGB2GRAY) blur = cv2.GaussianBlur(tmp,(5,5),0) if arg_binaryMethod== 0: ret, thresholdedImg= cv2.threshold(blur.copy() , self.threshold_graylevel, 255 , 0) elif arg_binaryMethod == 1: ret,thresholdedImg = cv2.threshold(blur.copy(),0 ,255 ,cv2.THRESH_BINARY+cv2.THRESH_OTSU) elif arg_binaryMethod== 2: thresholdedImg = cv2.adaptiveThreshold(blur.copy(),255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,5,0) result = cv2.cvtColor(thresholdedImg, cv2.COLOR_GRAY2RGB) ctrs, hier = cv2.findContours(thresholdedImg, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) ctrs = filter(lambda x : cv2.contourArea(x) > self.threshold_size , ctrs) rects = [[cv2.boundingRect(ctr) , ctr] for ctr in ctrs] for rect , cntr in rects: cv2.drawContours(result, [cntr], 0, (0, 128, 255), 3) if arg_export_index: cv2.imwrite(arg_export_path+ arg_export_filename+'.jpg', result) print "Get Contour success" return result
def adaptive_thresholding(img): # adaptive mean binary threshold th4 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,2) # adaptive gaussian thresholding th5 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2) return th5
def imgThresh(img): newIMG = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\ cv2.THRESH_BINARY,7,2) return newIMG
def convert_to_linedrawing(self, luminous_image_data): linedrawing = cv2.adaptiveThreshold(luminous_image_data, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2) return linedrawing
def process_captcha(self, image): """ TODO: DOC """ cv2_img = cv2.cvtColor(numpy.array(image), cv2.COLOR_BGR2GRAY) # Find the threshold of the image so that we can identify contours. ret, thresh = cv2.threshold( cv2_img, 127, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C ) # Find the contours of the image _, contours, hierarchy = cv2.findContours( thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE ) # Find the largest contour in the image with 4 points. This is the # rectangle that is required to crop to for the captcha. largest_contour = None for contour in contours: if (len(cv2.approxPolyDP(contour, 0.1*cv2.arcLength(contour, True), True)) == 4) and (2500 < cv2.contourArea(contour) < 4000): if isinstance(largest_contour, type(None)): largest_contour = contour continue if cv2.contourArea(contour) > cv2.contourArea(largest_contour): largest_contour = contour # If we don't have a matching contour, don't try to crop and such if isinstance(largest_contour, type(None)): return None # If we do have a matching contour, build the rectangle crop_x, crop_y, crop_width, crop_height = cv2.boundingRect( largest_contour ) # Crop down to the contour rectangle image = image.crop( ( crop_x, crop_y, crop_x + crop_width, crop_y + crop_height ) ) return image
def thresholdImage(gray,thr_type,thr,block_size=None,img=None): """ Where thr_type in {1,2,3,4} 1: Normal threshold 2: Otsu 3: Adaptive (mean) 4: Adaptive (Gaussian) More thresholds: Using two thresholds taking into account that most pixels are from the floor (Trying to don't erase black cars) 5: Double threshold (using percentiles) 6: Double threshold (using manually set values) """ if thr_type == 1: ret,thr = cv2.threshold(gray,thr,255,cv2.THRESH_BINARY) return thr elif thr_type == 2: ret,thr = cv2.threshold(gray,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) # Black/red cars desapeared. Good for Segmentation of background return thr elif thr_type == 3: return cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,block_size,2) # Less noise, but can't recognize all cars elif thr_type == 4: return cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,block_size,2) # More noise, more cars elif thr_type == 5: firstQ = np.percentile(gray2,65) # Return de value of the pixel that corresponds to the 65 percent of all sorted pixels in grayscale secondQ = np.percentile(gray2,50) thirdQ = np.percentile(gray2,35) return applyThreshold(gray,firstQ,thirdQ) elif thr_type == 6: return applyThreshold(gray,40,113) elif thr_type == 7: rows,col = img[:,:,0].shape r1,g1,b1 = getChannels(gray) # Actually is not grayscale but a BGR image (just a name) r2,g2,b2 = getChannels(img) res = np.zeros((rows,col)) for i in range(0,rows): for j in range(0,col): rDif = abs(int(r1[i,j]) - int(r2[i,j])) gDif = abs(int(g1[i,j]) - int(g2[i,j])) bDif = abs(int(b1[i,j]) - int(b2[i,j])) if rDif >= thr or gDif >= thr or bDif >= thr: res[i,j] = 0 else: res[i,j] = 255 return res else: return None
def apply_filters(self, frame): """Apply specified filters to frame. Args: frame (np.ndarray): frame to be modified. Returns: n_frame (np.ndarray): modified frame. """ n_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) if 'g-blur' in self.filters: n_frame = cv2.GaussianBlur(n_frame, (5,5), 0) if 'b-filtering' in self.filters: n_frame = cv2.bilateralFilter(n_frame, 9, 75, 75) if 't_adaptive' in self.filters: n_frame = cv2.adaptiveThreshold(n_frame, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 115, 1) if 'otsu' in self.filters: _, n_frame = cv2.threshold(n_frame, 125, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) if 'canny' in self.filters: n_frame = cv2.Canny(n_frame, 100, 200) if 'b-subtraction' in self.filters: n_frame = self.subtractor.apply(frame) n_frame = cv2.cvtColor(n_frame, cv2.COLOR_GRAY2BGR) return n_frame
def binarize(self): # ????????? ????? ??? = retval2, thres = cv2.threshold(data, 50,70,cv2.THRESH_BINARY) thres = cv2.blur(thres, (50, 50)) # ????????? ???????? = a = cv2.adaptiveThreshold(self.data, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 125, 1) # a = cv2.adaptiveThreshold(a, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 55, 1) # retval2, a = cv2.threshold(self.data, 90, 255, cv2.THRESH_BINARY) # a1 = np.median(a, 0) # plt.hist(a1, 256, range=[0, 255], fc='k', ec='k') # plt.show() self.data = a
def Bin(data): # ????????? ????? ??? = retval2, thres = cv2.threshold(data, 50,70,cv2.THRESH_BINARY) thres = cv2.blur(thres, (50, 50)) # ????????? ???????? = # retval2, thres = cv2.threshold(data,240,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) # thres =cv2.adaptiveThreshold(data, 255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 0) retval2, thres = cv2.threshold(data, 120,127,cv2.THRESH_BINARY) # thres = cv2.blur(thres, (50, 50)) return thres
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
def tresholdify(self, pic): self.log.info("applying threshold filter") pic = cv2.cvtColor(pic, cv2.COLOR_BGR2GRAY) pic = cv2.GaussianBlur(pic, (5, 5), 0) pic = cv2.adaptiveThreshold(pic, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 115, 1) return pic
def detect(self, image, mask = None): b,g,r = cv2.split(image) difference = cv2.subtract(r, b) difference = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # ADAPTIVE_THRESH_GAUSSIAN_C or ADAPTIVE_THRESH_MEAN_C return cv2.adaptiveThreshold(difference, 1, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, Configuration.adaptive_block_size, Configuration.adaptive_threshold)
def binarize(img=get_sample_image()): thresh = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 4) return thresh
def binarialization(arg_frame, arg_binaryMethod, arg_thresholdValue= 100): if len(arg_frame.shape)==3: tmp = cv2.cvtColor(arg_frame, cv2.COLOR_RGB2GRAY) else: tmp= arg_frame.copy() # Otsu's thresholding after Gaussian filtering blur = cv2.GaussianBlur(tmp,(5,5),0) if arg_binaryMethod== 0: ret, thresholdedImg= cv2.threshold(blur.copy() , arg_thresholdValue, 255 , 0) elif arg_binaryMethod == 1: ret,thresholdedImg = cv2.threshold(blur.copy(),0 ,255 ,cv2.THRESH_BINARY+cv2.THRESH_OTSU) elif arg_binaryMethod== 2: thresholdedImg = cv2.adaptiveThreshold(blur.copy(),255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,5,0) return thresholdedImg
def adaptive_binarize_py(x, block_size=5, C=33.8): "Works like an edge detector." # ADAPTIVE_THRESH_GAUSSIAN_C, ADAPTIVE_THRESH_MEAN_C # THRESH_BINARY, THRESH_BINARY_INV import cv2 ret_imgs = opencv_wrapper(x, cv2.adaptiveThreshold, [255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, block_size, C]) return ret_imgs
def threshold_image_for_tape(image): """ Thresholds image for reflective tape with light shined on it. This means it looks for pixels that are almost white, makes them white, and makes everything else black. Parameters: :param: `image` - the source image to threshold from """ orig_image = numpy.copy(image) # print orig_image.size orig_image = cv2.medianBlur(orig_image, 3) # orig_image[orig_image > 100] = 255 # return orig_image[orig_image > 100] height, width = orig_image.shape[0], orig_image.shape[1] eight_bit_image = numpy.zeros((height, width, 1), numpy.uint8) cv2.inRange(orig_image, (B_RANGE[0], G_RANGE[0], R_RANGE[0], 0), (B_RANGE[1], G_RANGE[1], R_RANGE[1], 100), eight_bit_image) # # eight_bit_image = cv2.adaptiveThreshold(orig_image, # # 255, # # cv2.ADAPTIVE_THRESH_GAUSSIAN_C, # # cv2.THRESH_BINARY, # # 8, # # 0) # cv2.medianBlur(eight_bit_image, 9) return eight_bit_image
def th2(self,img): # ????? # ???? # median = cv2.medianBlur(thresh,3) # img_blur = cv2.GaussianBlur(img_gray, (m_blurBlock,m_blurBlock), 0) img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) thresh = cv2.adaptiveThreshold(img_gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 19) return thresh # ?????
def adaptiveThresholding(gray=None, neighbor=5, blur=False, k_size=3): if(blur): gray = cv2.GaussianBlur(gray, (k_size, k_size), 0) return cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, neighbor, 1)
def getAdaptiveThreshold(self, image): return cv2.adaptiveThreshold(image,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C ,\ cv2.THRESH_BINARY,21,0)
def _clean_image(self) -> None: self._img = cv2.medianBlur(self._img, ksize=3) self._img = cv2.adaptiveThreshold(self._img, maxValue=255, adaptiveMethod=cv2.ADAPTIVE_THRESH_GAUSSIAN_C, thresholdType=cv2.THRESH_BINARY, blockSize=11, C=2) self.intermediate_images.append(NamedImage(self._img.copy(), 'Clean Image'))
def __init__(self): """initializes all values to presets or None if need to be set """ self.__lastImage0 = numpy.ndarray([]) self.__source0 = None self.threshold_moving_output = None self.__blur_input = self.threshold_moving_output self.__blur_type = BlurType.Box_Blur self.__blur_radius = 6 self.blur_output = None self.__cv_threshold_src = self.blur_output self.__cv_threshold_thresh = 12.0 self.__cv_threshold_maxval = 255.0 self.__cv_threshold_type = cv2.THRESH_BINARY self.cv_threshold_output = None self.__cv_adaptivethreshold_src = self.cv_threshold_output self.__cv_adaptivethreshold_maxvalue = 255.0 self.__cv_adaptivethreshold_adaptivemethod = cv2.ADAPTIVE_THRESH_GAUSSIAN_C self.__cv_adaptivethreshold_thresholdtype = cv2.THRESH_BINARY self.__cv_adaptivethreshold_blocksize = 127.0 self.__cv_adaptivethreshold_c = 0.0 self.cv_adaptivethreshold_output = None self.__find_blobs_input = self.cv_adaptivethreshold_output self.__find_blobs_min_area = 56.0 self.__find_blobs_circularity = [0.0, 1.0] self.__find_blobs_dark_blobs = False self.find_blobs_output = None
def render(self,frame): return cv2.medianBlur(cv2.adaptiveThreshold(cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY),255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,27,3),5)
def find_contours(img): ''' :param img: (numpy array) :return: all possible rectangles (contours) ''' img_blurred = cv2.GaussianBlur(img, (5, 5), 1) # remove noise img_gray = cv2.cvtColor(img_blurred, cv2.COLOR_BGR2GRAY) # greyscale image # cv2.imshow('', img_gray) # cv2.waitKey(0) # Apply Sobel filter to find the vertical edges # Find vertical lines. Car plates have high density of vertical lines img_sobel_x = cv2.Sobel(img_gray, cv2.CV_8UC1, dx=1, dy=0, ksize=3, scale=1, delta=0, borderType=cv2.BORDER_DEFAULT) # cv2.imshow('img_sobel', img_sobel_x) # Apply optimal threshold by using Oslu algorithm retval, img_threshold = cv2.threshold(img_sobel_x, 0, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY) # cv2.imshow('s', img_threshold) # cv2.waitKey(0) # TODO: Try to apply AdaptiveThresh # Size of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3, 5, 7, and so on. # gaus_threshold = cv2.adaptiveThreshold(img_gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 115, 1) # cv2.imshow('or', img) # cv2.imshow('gaus', gaus_threshold) # cv2.waitKey(0) # Define a stuctural element as rectangular of size 17x3 (we'll use it during the morphological cleaning) element = cv2.getStructuringElement(shape=cv2.MORPH_RECT, ksize=(17, 3)) # And use this structural element in a close morphological operation morph_img_threshold = deepcopy(img_threshold) cv2.morphologyEx(src=img_threshold, op=cv2.MORPH_CLOSE, kernel=element, dst=morph_img_threshold) # cv2.dilate(img_threshold, kernel=np.ones((1,1), np.uint8), dst=img_threshold, iterations=1) # cv2.imshow('Normal Threshold', img_threshold) # cv2.imshow('Morphological Threshold based on rect. mask', morph_img_threshold) # cv2.waitKey(0) # Find contours that contain possible plates (in hierarchical relationship) contours, hierarchy = cv2.findContours(morph_img_threshold, mode=cv2.RETR_EXTERNAL, # retrieve the external contours method=cv2.CHAIN_APPROX_NONE) # all pixels of each contour plot_intermediate_steps = False if plot_intermediate_steps: plot(plt, 321, img, "Original image") plot(plt, 322, img_blurred, "Blurred image") plot(plt, 323, img_gray, "Grayscale image", cmap='gray') plot(plt, 324, img_sobel_x, "Sobel") plot(plt, 325, img_threshold, "Threshold image") # plot(plt, 326, morph_img_threshold, "After Morphological filter") plt.tight_layout() plt.show() return contours
def find_goal(frame): # converting to HSV hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) #show_image(hsv) lower_blue = np.array([113, 40, 29]) upper_blue = np.array([123, 180, 255]) mask = cv2.inRange(hsv, lower_blue, upper_blue) #show_image(mask) result = cv2.bitwise_and(frame, frame, mask=mask) #show_image(result) blur = cv2.blur(result, (5, 5)) bw = cv2.cvtColor(blur, cv2.COLOR_HSV2BGR) bw2 = cv2.cvtColor(bw, cv2.COLOR_BGR2GRAY) ret, th3 = cv2.threshold(bw2, 30, 255, cv2.THRESH_BINARY) # th3 = cv2.adaptiveThreshold(bw2,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\ # cv2.THRESH_BINARY,11,2) edges = cv2.Canny(th3, 100, 200) th4 = copy.copy(th3) perimeter = 0 j = 0 image, contours, hierarchy = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) # print len(contours) # if(len(contours) > 5): # continue cnt = np.array([]) for i in range(len(contours)): if (perimeter < cv2.contourArea(contours[i])): perimeter = cv2.contourArea(contours[i]) j = i; cnt = contours[j] if (len(cnt) == 0): return (-1, -1) cv2.drawContours(frame, cnt, -1, (0, 255, 0), 3) x = 0 y = 0 #print 'find goal' #print len(cnt), j #print cnt for i in range(len(cnt)): x = x + cnt[i][0][0] y = y + cnt[i][0][1] x = x/len(cnt) y = y/len(cnt) #print x, y x = int(x) y = int(y) cv2.circle(frame, (x, y), 5, (255, 0, 255), -1) #cv2.imshow('image', frame) #k = cv2.waitKey(0) return (int(x), int(y))
def find_goal(img): # converting to HSV frame = copy.copy(img) hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) #show_image(hsv) lower_blue = np.array([113, 40, 29]) upper_blue = np.array([123, 180, 255]) mask = cv2.inRange(hsv, lower_blue, upper_blue) #show_image(mask) result = cv2.bitwise_and(frame, frame, mask=mask) #show_image(result) blur = cv2.blur(result, (5, 5)) bw = cv2.cvtColor(blur, cv2.COLOR_HSV2BGR) bw2 = cv2.cvtColor(bw, cv2.COLOR_BGR2GRAY) ret, th3 = cv2.threshold(bw2, 30, 255, cv2.THRESH_BINARY) # th3 = cv2.adaptiveThreshold(bw2,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\ # cv2.THRESH_BINARY,11,2) edges = cv2.Canny(th3, 100, 200) th4 = copy.copy(th3) perimeter = 0 j = 0 image, contours, hierarchy = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) # print len(contours) # if(len(contours) > 5): # continue cnt = np.array([]) for i in range(len(contours)): if (perimeter < cv2.contourArea(contours[i])): perimeter = cv2.contourArea(contours[i]) j = i; cnt = contours[j] if (len(cnt) == 0): return (-1, -1) cv2.drawContours(frame, cnt, -1, (0, 255, 0), 3) x = 0 y = 0 #print 'find goal' #print len(cnt), j #print cnt for i in range(len(cnt)): x = x + cnt[i][0][0] y = y + cnt[i][0][1] x = x/len(cnt) y = y/len(cnt) #print x, y x = int(x) y = int(y) cv2.circle(frame, (x, y), 5, (255, 0, 255), -1) cv2.imshow('image', frame) cv2.imwrite('goal.jpg', frame) k = cv2.waitKey(0) return (int(x), int(y))
def segment(self): self.im_gray = cv2.medianBlur(self.im_gray, 5) # Apply adaptive threshold with binary_inv thresh = cv2.adaptiveThreshold(self.im_gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2) # apply some dilation and erosion to join the gaps thresh = cv2.dilate(thresh, None, iterations=3) thresh = cv2.erode(thresh, None, iterations=2) # finding contours im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) ''' cropped is a dictionary with (cx, cy) centroid tuples as keys, and cropped images as values centroids is a list of the same centroid tuples, (cx, cy) - This was done because it was not possible to sort the dictionary directly using tuples as keys using the sort(dict) function. - Instead, (cx, cy) was stored in the centroids list, and the list in turn was sorted using centroids.sort(). - The list is then iterated upon to get tuples in order... - Each tuple iterated upon acts as a key for the dictionary, fetching the cropped images in order ''' cropped = {(0, 0): '0'} centroids = [(0, 0)] for cnt in contours: x, y, w, h = cv2.boundingRect(cnt) # finding centroid coordinates, so that it can be the basis of sorting cropped images M = cv2.moments(cnt) cx = int(M['m10'] / M['m00']) cy = int(M['m01'] / M['m00']) # storing centroid tuple and cropped image in dictionary cropped[(cx, cy)] = self.im_gray[y:y + h, x:x + w] # inserting centroid tuples to a list centroids.append((cx, cy)) # since (0, 0) was only a placeholder del cropped[(0, 0)] centroids.remove((0, 0)) # sorting the centroid list centroids.sort() segments = [] for c in centroids: segments.append(cropped[c]) return segments
def binaryMask(frame, x0, y0, width, height ): global guessGesture, visualize, mod, lastgesture, saveImg cv2.rectangle(frame, (x0,y0),(x0+width,y0+height),(0,255,0),1) roi = frame[y0:y0+height, x0:x0+width] gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray,(5,5),2) #blur = cv2.bilateralFilter(roi,9,75,75) th3 = cv2.adaptiveThreshold(blur,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY_INV,11,2) ret, res = cv2.threshold(th3, minValue, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU) #ret, res = cv2.threshold(blur, minValue, 255, cv2.THRESH_BINARY +cv2.THRESH_OTSU) if saveImg == True: saveROIImg(res) elif guessGesture == True: retgesture = myNN.guessGesture(mod, res) if lastgesture != retgesture : lastgesture = retgesture #print lastgesture ## Checking for only PUNCH gesture here ## Run this app in Prediction Mode and keep Chrome browser on focus with Internet Off ## And have fun :) with Dino if lastgesture == 3: jump = ''' osascript -e 'tell application "System Events" to key code 49' ''' #jump = ''' osascript -e 'tell application "System Events" to key down (49)' ''' os.system(jump) print myNN.output[lastgesture] + "= Dino JUMP!" #time.sleep(0.01 ) #guessGesture = False elif visualize == True: layer = int(raw_input("Enter which layer to visualize ")) cv2.waitKey(1) myNN.visualizeLayers(mod, res, layer) visualize = False return res #%%