def remove_noise(self): height, width, bytes_per_component = self.image.shape bytes_per_line = 3 * width self.noise_image = np.zeros(self.image.shape, np.uint8) cv2.medianBlur(self.image, 3, self.noise_image) demo_utils.show_cvimage_to_label(self.noise_image, self.noise_label)
def process(filename): print(filename) filename = 'old.png' image = cv2.imread(filename) # display_image(image) # display_image(image) # convert the image to greyscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # apply blur for noise reduction gray = cv2.medianBlur(gray, 7) # display_image(gray) # print(gray.shape) # rows = gray.shape[0] # # apply Hough gradient # circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1.2, 400) # circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, rows / 8, param1=200, param2=37, minRadius=1, maxRadius=300) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) img = cv2.medianBlur(gray, 17) # display_image(cimg) # detect circles in the image circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=30, minRadius=0, maxRadius=0) balls = [] print(circles) if circles is not None: circles = np.uint16(np.around(circles[0, :]).astype("int")) for (x, y, r) in circles: color = get_color(image, x, y, r) balls.append([x, y, r, color]) center = (x, y) # marking detected circles cv2.circle(image, center, 1, (0, 100, 100), 2) cv2.circle(image, center, r, (255, 255, 255), 2) print(balls) print(len(balls)) display_image(image)
def oilPaint(image, saturation=1.1, brightness=1.05): laplacianFilter = np.array( [[-1, -1, -1, -1, -1, -1, -1], [-1, 0, 0, 0, 0, 0, -1], [-1, 0, 0, 0, 0, 0, -1], [-1, 0, 0, 26, 0, 0, -1], [-1, 0, 0, 0, 0, 0, -1], [-1, 0, 0, 0, 0, 0, -1], [-1, -1, -1, -1, -1, -1, -1]], np.float32) / 2.0 image_median = cv2.medianBlur(image, 7) image_oil = cv2.filter2D(image_median, -1, laplacianFilter) for i in range(2): image_oil = cv2.medianBlur(image_oil, 3) image_oil = modulateSV(image_oil, saturation, brightness) return image_oil
def method4(): while c.isOpened(): rd, image = c.read() if rd: # ---------> 前處理 <---------- m0 = cv2.medianBlur(image, 5) m1 = m0[:, :, 2] # 取 紅色通道 # ---------> 二值化 <---------- th, m2 = cv2.threshold(m1, 60, 255, cv2.THRESH_BINARY) m3 = cv2.bitwise_not(m2) # ---------> 最小方框點 <---------- x, y, w, h = cv2.boundingRect(m3) # ---------> 畫方框在原始圖片上 <---------- cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 255), 3) cv2.imshow("image", image) cv2.imshow("m0", m0) cv2.imshow("m1", m1) cv2.imshow("m2", m2) cv2.imshow("m3", m3) else: break if cv2.waitKey(10) != -1: break
def skin_extract(image): img_HSV = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) #skin color range for hsv color space HSV_mask = cv2.inRange(img_HSV, (0, 15, 0), (17, 170, 255)) #cv2.imshow('HSV mask_before',HSV_mask) #cv2.imwrite('HSV mask_before.jpg',HSV_mask) HSV_mask = cv2.morphologyEx(HSV_mask, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8)) #cv2.imshow('HSV mask',HSV_mask) #cv2.imwrite('HSV mask.jpg',HSV_mask) #converting from gbr to YCbCr color space img_YCrCb = cv2.cvtColor(image, cv2.COLOR_BGR2YCrCb) #skin color range for hsv color space YCrCb_mask = cv2.inRange(img_YCrCb, (0, 135, 85), (255, 180, 135)) #cv2.imshow('YCrCb_mask_before',YCrCb_mask) #cv2.imwrite('YCrCb_mask_before.jpg',YCrCb_mask) YCrCb_mask = cv2.morphologyEx(YCrCb_mask, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8)) #cv2.imshow('YCrCb_mask',YCrCb_mask) #cv2.imwrite('YCrCb_mask.jpg',YCrCb_mask) #merge skin detection (YCbCr and hsv) global_mask = cv2.bitwise_and(YCrCb_mask, HSV_mask) #cv2.imshow('global_mask_before',YCrCb_mask) cv2.imwrite('global_mask_befores.jpg', YCrCb_mask) global_mask = cv2.medianBlur(global_mask, 3) global_mask = cv2.morphologyEx(global_mask, cv2.MORPH_OPEN, np.ones((4, 4), np.uint8)) #cv2.imshow('global_mask',YCrCb_mask) cv2.imwrite('global_mask.jpg', YCrCb_mask) return YCrCb_mask
def extract_text_lines(img, output_dir): """ img - image from which the text lines are extracted output_dir - directory where the extracted lines should be saved """ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) blur = cv2.medianBlur(gray, 5) thresh = cv2.adaptiveThreshold(blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 5, 5) kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (16, 2)) dilate = cv2.dilate(thresh, kernel, iterations=2) rotated, rot_dilated = find_text_angle(dilate, img) cnts = cv2.findContours(rot_dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) if len(cnts) == 2: cnts = cnts[0] else: cnts = cnts[1] lines_path = os.path.join(output_dir, 'lines') if not os.path.exists(lines_path): os.makedirs(lines_path) for line_idx, line in enumerate(cnts, start=-len(cnts)): x, y, w, h = cv2.boundingRect(line) roi = rotated[y:y + h, x:x + w] filename = 'line' + str(line_idx) + '.jpg' save_img(lines_path, filename=filename, img=roi)
def image_processing(image): PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) image_path = os.path.dirname(PROJECT_ROOT)+"\media"+"\\"+str(image) image = cv2.imread(image_path) angle, rotated = correct_skew(image) gray = cv2.cvtColor(rotated,cv2.COLOR_BGR2GRAY) thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1] horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (40,1)) remove_horizontal = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, horizontal_kernel, iterations=2) cnts = cv2.findContours(remove_horizontal, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = cnts[0] if len(cnts) == 2 else cnts[1] for c in cnts: cv2.drawContours(rotated, [c], -1, (255,255,255), 5) vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1,40)) remove_vertical = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, vertical_kernel, iterations=2) cnts = cv2.findContours(remove_vertical, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = cnts[0] if len(cnts) == 2 else cnts[1] for c in cnts: cv2.drawContours(rotated, [c], -1, (255,255,255), 5) gray = cv2.cvtColor(rotated,cv2.COLOR_BGR2GRAY) filter1 = cv2.medianBlur(gray,5) filter2 = cv2.GaussianBlur(filter1,(5,5),0) dst = cv2.fastNlMeansDenoising(filter2,None,17,9,17) th1 = cv2.adaptiveThreshold(dst,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2) return th1
def cartoon(self, image): ''' Cartoonise Image! Datatypes: image:nparray format BGR ''' numdown, numbilateral = 2, 7 color = image for _ in range(numdown): color = cv2.pyrDown(color) for _ in range(numbilateral): color = cv2.bilateralFilter(color, d=9, sigmaColor=9, sigmaSpace=7) for _ in range(numdown): color = cv2.pyrUp(color) cartoon = cv2.bitwise_and( color, cv2.cvtColor( cv2.adaptiveThreshold(cv2.medianBlur( cv2.cvtColor(image, cv2.COLOR_RGB2GRAY), 7), 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, blockSize=9, C=2), cv2.COLOR_GRAY2RGB)) cartoon = cv2.cvtColor(cartoon, cv2.COLOR_BGR2RGB) return cartoon
def blurr_face(): global output try: output = cv2.imread(root.filepath) roi = output.copy() dir_path = os.path.dirname(os.path.realpath(__file__)) face_cascade = cv2.CascadeClassifier( dir_path + '\\haarcascade_frontalface_alt.xml') gray = cv2.cvtColor(output, cv2.COLOR_RGB2GRAY) face_rects = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=3) for (x, y, wi, h) in face_rects: roi = roi[y:y + h, x:x + wi] blurred_roi = cv2.medianBlur(roi, 99) output[y:y + h, x:x + wi] = blurred_roi im = ImageFrame(root, img=output, height=w.Canvas1.winfo_height(), width=w.Canvas1.winfo_width()) im.place(relx=0.014, rely=0.462) im.update() except: messagebox.showerror("Something Went Wrong !", "Make sure Image path is added right") sys.stdout.flush()
def detect( self, frame : numpy.ndarray ): # Convert to foreground mask, close gaps, remove noise. fg_mask = self.back_sub.apply( frame ) fg_mask = cv2.morphologyEx( fg_mask, cv2.MORPH_CLOSE, self.kernel ) fg_mask = cv2.medianBlur( fg_mask, self.blur ) # Flatten mask to B&W. ret, fg_mask = cv2.threshold( fg_mask, self.threshold, 255, cv2.THRESH_BINARY ) # Find object contours/areas. contours, hierarchy = cv2.findContours( fg_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE )[-2:] areas = [cv2.contourArea(c) for c in contours] if 0 < len( areas ): max_idx = numpy.argmax( areas ) cnt_iter = contours[max_idx] rect_x, rect_y, rect_w, rect_h = cv2.boundingRect( cnt_iter ) return self.handle_movement( frame, rect_x, rect_y, rect_w, rect_h ) return None
def pretty_blur_map(blur_map: np.array, sigma: int = 5, min_abs: float = 0.5): abs_image = np.abs(blur_map).astype(np.float32) abs_image[abs_image < min_abs] = min_abs abs_image = np.log(abs_image) cv2.blur(abs_image, (sigma, sigma)) return cv2.medianBlur(abs_image, sigma)
def getCropMask(color, depth, hue): ''' 拿到掩模 ''' ### H-[65 98] S-[33 255] V-[117 255] ### ## 原 [30,100,40] ## [100,255,255] hsv = cv2.cvtColor(color, cv2.COLOR_BGR2HSV) lower_g = np.array([hue-20,33,30]) upper_g = np.array([hue+20,255,255]) mask = cv2.inRange(hsv, lower_g, upper_g) mask = cv2.medianBlur(mask, 5) kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5)) mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel) ''' 去除掩模小的连通域 ''' if(cv2.__version__[0] == '4'): contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) else: _, contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) boundaries = [] for con in contours: if(cv2.contourArea(con) > 1000): boundaries.append(con) cv2.drawContours(mask, [con], 0, 255, -1) else: cv2.drawContours(mask, [con], 0, 0, -1) ''' 将掩模与深度做与运算 ''' depth_bin = np.uint8(depth>0)*255 mask = cv2.bitwise_and(mask, depth_bin) return(mask)
def extract_text_chars(img, output_dir): """ img - image from which the individual chars are extracted output_dir - directory where the extracted lines should be saved """ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) blur = cv2.medianBlur(gray, 7) thresh = cv2.adaptiveThreshold(blur, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 7, 11) kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 7)) dilate = cv2.dilate(thresh, kernel, iterations=1) cnts = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) if len(cnts) == 2: cnts = cnts[0] else: cnts = cnts[1] chars_path = os.path.join(output_dir, 'chars') if not os.path.exists(chars_path): os.makedirs(chars_path) for char_idx, character in enumerate(cnts, start=-len(cnts)): x, y, w, h = cv2.boundingRect(character) roi = img[y:y + h, x:x + w] filename = 'char' + str(char_idx) + '.jpg' save_img(chars_path, filename=filename, img=roi)
def contours(img, adaptive=True): """ Finds contours given an img :param img: image :return contours: contours of the image :return hierarchy: """ blur = cv2.medianBlur(img, 5) grayscale = cv2.cvtColor(blur, cv2.COLOR_BGR2GRAY) if adaptive is False: _, thresh = cv2.threshold(grayscale, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU) else: thresh = cv2.adaptiveThreshold(grayscale, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 3, 2) # kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (25,25)) # opening = cv2.morpholfirst_frameyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=3) contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) return contours, hierarchy
def blur_(images, m=2): # 設置3x3矩陣每個元素為1/9 r = 5 kernel = np.ones((r, r), np.float32) / (r * r) out = [] if m == 1: for i in range(len(images)): # 將圖片經過3x3矩陣平均模糊化去雜訊 dst = cv2.filter2D(images[i], -1, kernel) out.append(dst) elif m == 2: for i in range(len(images)): # 將圖片經過3x3矩陣平均模糊化去雜訊 dst = cv2.medianBlur(images[i], r) out.append(dst) else: for i in range(len(images)): # 將圖片做高斯模糊化去雜訊 dst = cv2.GaussianBlur(images[i], (r, r), 1) out.append(dst) return out
def red_filtering(self, frame): # Adapted from # https://stackoverflow.com/questions/42840526/opencv-python-red-ball-detection-and-tracking # # convert the input stream into HSV color space hsv_conv_img = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # then the image is blurred hsv_blurred_img = cv2.medianBlur(hsv_conv_img, 9, 3) # because hue wraps up and to extract as many "red objects" as possible, # we define lower and upper boundaries for brighter and for darker red shades bright_red_mask = cv2.inRange(hsv_blurred_img, self.bright_red_lower_bounds, self.bright_red_upper_bounds) dark_red_mask = cv2.inRange(hsv_blurred_img, self.dark_red_lower_bounds, self.dark_red_upper_bounds) # after masking the red shades out, I add the two images weighted_mask = cv2.addWeighted(bright_red_mask, 1.0, dark_red_mask, 1.0, 0.0) # then the result is blurred blurred_mask = cv2.GaussianBlur(weighted_mask, (9, 9), 3, 3) # some morphological operations (closing) to remove small blobs erode_element = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) dilate_element = cv2.getStructuringElement(cv2.MORPH_RECT, (8, 8)) eroded_mask = cv2.erode(blurred_mask, erode_element) dilated_mask = cv2.dilate(eroded_mask, dilate_element) return dilated_mask
def image_process(img): """ Binarizes and skeletonizes the image. Args: img Returns: target_point """ width = img.shape[1] height = img.shape[0] roi = img[int(height / 3 * 2):int(height / 10 * 9), 0:width] if DEBUG: cv.imwrite("ROI.jpg", roi) img_bin = binarize(roi) ele = cv.getStructuringElement(cv.MORPH_ELLIPSE, (3, 3)) img_bin_rev = cv.morphologyEx(255 - img_bin, cv.MORPH_OPEN, ele) img_bin_rev = cv.medianBlur(img_bin_rev, 11) skel = morphology.skeletonize(img_bin_rev // 255).astype(np.uint8) * 255 img_bin_rev[skel == 255] = 120 if DEBUG: cv.imwrite("img_bin_rev.jpg", img_bin_rev) cv.imshow("skel", skel) cv.waitKey(10000) return skel, img_bin_rev # for test
def thresholding(img_gray): _, img_th = cv2.threshold(img_gray,np.average(img_gray)-32,255,cv2.THRESH_BINARY) img_th2 = cv2.adaptiveThreshold(img_gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY_INV,21,7) img_th3 = np.bitwise_and(img_th, img_th2) img_th4 = cv2.subtract(img_th2, img_th3) for i in range(5): img_th4 = cv2.medianBlur(img_th4, 5) return img_th4
def MedianFilter(self, path, file_name): try: img = cv2.imread(path + file_name, session['rg_value']) median = cv2.medianBlur(img, session['kz_value']) f_name = str(randint(1000000000, 9999999999)) + session['org_name'] cv2.imwrite(path + f_name, median) return f_name except: return None
def cartonize_image(our_image): new_img = np.array(our_image.convert('RGB')) img = cv2.cvtColor(new_img, 1) gray = cv2.cvtColor(new_img, cv2.COLOR_BGR2GRAY) gray = cv2.medianBlur(gray, 5) edges = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 9) color = cv2.bilateralFilter(img, 9, 300, 300) cartoon = cv2.bitwise_and(color, color, mask=edges) return cartoon
def Median_filter(self): img = cv.imread('Cat.png') median = cv.medianBlur(img, 7) plt_img = img[:,:,::-1] plt.figure('origin') plt.imshow(plt_img) plt_median = median[:,:,::-1] plt.figure('median') plt.imshow(plt_median) plt.show()
def imageSmoothingMedianImg(self): try: img = cv2.imread(self.filename) blur = cv2.medianBlur(img, 5) cv2.imwrite('img/dist/median.png', blur, [cv2.IMWRITE_JPEG_QUALITY, 100]) cv2.waitKey(0) cv2.destroyAllWindows() except: pass
def detect_and_blur_faces(img): face_img = img.copy() frontalface_rects = frontalface_cascade.detectMultiScale(face_img, scaleFactor=1.3, minNeighbors=5) profileface_rects = profileface_cascade.detectMultiScale(face_img, scaleFactor=1.3, minNeighbors=6) for (x, y, w, h) in frontalface_rects: blur_face = cv.medianBlur(face_img[y:y + h, x:x + w], 51) face_img[y:y + h, x:x + w] = blur_face cv.rectangle(face_img, (x, y), (x + w, y + h), (255, 0, 0), 3) for (x, y, w, h) in profileface_rects: blur_face = cv.medianBlur(face_img[y:y + h, x:x + w], 51) face_img[y:y + h, x:x + w] = blur_face cv.rectangle(face_img, (x, y), (x + w, y + h), (255, 0, 0), 3) return face_img
def NoiseGMF(self, path, file_name): img = cv2.imread(path + file_name) if request.args.get('gs'): gauss_median = cv2.GaussianBlur( img, (session['kz_value'], session['kz_value']), 0) else: gauss_median = cv2.medianBlur(img, session['kz_value']) noise_img = self.sp_noise(gauss_median, 0.05) f_name = str(randint(1000000000, 9999999999)) + session['org_name'] cv2.imwrite(path + f_name, noise_img) return f_name
def interference_point(self): import numpy as np import matplotlib.pyplot as plt img = cv2.imread(self.img, 0) # 直接读为灰度图像 for i in range(2000): # 添加点噪声 temp_x = np.random.randint(0, img.shape[0]) temp_y = np.random.randint(0, img.shape[1]) img[temp_x][temp_y] = 255 blur = cv2.medianBlur(img, 5) plt.subplot(1, 2, 1), plt.imshow(img, 'gray') # 默认彩色,另一种彩色bgr plt.subplot(1, 2, 2), plt.imshow(blur, 'gray')
def median_blur(image, n, border=0): """apply a median blur of kernel size n to the image. :param image: input image :type image: cv2 image :param n: kernel size :type n: int :param border: what to do when the kernel overlaps the border, defaults to 0 :param border: int, optional :return: blurred image :rtype: cv2 image """ return cv2.medianBlur(image, n, border)
def Edge_detection(image): #Funkcija za detekciju rubova i kuteva slike ratio = image.shape[0] / 500.0 # orig = image.copy() # Manipuliramo veličinom slike kako bismo je mogli koristiti za image = imutils.resize(image, height = 500) # daljnju obradu gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # gray = cv2.GaussianBlur(gray, (5, 5), 0) # Pretavranje slike u crno-bijelu sliku te ju zamagljujemo img = cv2.medianBlur(gray,5) # kako bismo našli rubove papira threshold = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2) # Contours(threshold, ratio, orig) # Pozivanje funkcije u kojoj ćemo naći konture papira
def img_processing(IMG): IMG = cv2.medianBlur(IMG, 5) # Użycie adatptive threshold dla pozbycia się zbędnych wartości piskeli (binaryzacja) th1 = cv2.adaptiveThreshold(IMG, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 35, 5) # Zamkniecie i otwracie usuwa większąść szumu, lepiej widać zarys oka morph = cv2.morphologyEx(th1, cv2.MORPH_OPEN, cv2.getStructuringElement(2, (5, 5))) morph = cv2.morphologyEx(morph, cv2.MORPH_CLOSE, cv2.getStructuringElement(2, (3, 3))) return morph
def config(self, frame): """ Функция для задания настроек видеофайла """ width = frame.shape[1] height = frame.shape[0] # TODO: выбрать хороший фильтр blur = cv2.medianBlur(frame, 3) blob = cv2.dnn.blobFromImage(blur, 0.007843, (width, height), 127.5) self.net.setInput(blob) out = self.net.forward() return width, height, out
def main(img_path): """performs median filtering as per prac2 :param img: the path to an image :type img: str """ # read in the image image = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE) utils.show('before filter', image) # apply a median filter to the image of size k = 5 filtered = cv2.medianBlur(image, 5) utils.show('after filter', filtered)