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 dupImageByColor(in_frame, hue, sat, val, torg, t): out_img = cv2.cvtColor(in_frame, cv2.COLOR_BGR2HSV) # out_img = cv2.inRange(out_img, (hue[0], sat[0], val[0]), (hue[1], sat[1], val[1])) out_img = cv2.blur(out_img, (3, 3)) # # masking out the area that we wanted by just taking an entire slice of the area and leave it in the 'out' image #out_img = out_img[_y1:_y2, _x1:_x2] # also draw this slice on the original image in Red (BGR) #cv2.rectangle(out_img, _mask_p1, _mask_p2, (0,0,255), 1) # Now, let's find the contour - we only keeping/using contours for this time contours, _ = cv2.findContours(out_img, mode=cv2.RETR_EXTERNAL, method=cv2.CHAIN_APPROX_SIMPLE) maxcontourarea = 0.0 if len(contours) > 0: c = max(contours, key=cv2.contourArea) maxcontourarea = cv2.contourArea(c) #for c in contours: # cv2.drawContours(out_img, c, 0, (0,150,150), 1) # out_img = cv2.cvtColor(out_img, cv2.COLOR_HSV2BGR) # cv2.putText(in_frame, str(t) + ": " + str(maxcontourarea), torg, cv2.FONT_HERSHEY_PLAIN, 1, (0,0,0)) return (out_img, maxcontourarea)
def randomBlur(self, bgr): ''' 随机模糊 ''' if random.random() < 0.5: bgr = cv2.blur(bgr, (5, 5)) return bgr
def add_rain(self, image: Image.Image) -> Image.Image: """The function takes a image and adds rain or snow. Args: image (PIL.Image.Image): The input is a open PIL image Returns: PIL.Image.Image: The output is a open PIL image """ image.load() image = np.asarray(image, dtype="int32") imshape = image.shape slant_extreme = 5 slant = np.random.randint(-slant_extreme, slant_extreme) drop_color = self.color self.rain_drops = self.generate_random_lines(imshape, slant) rand = random.uniform(0.5, 1) for rain_drop in self.rain_drops: cv2.line(image, (rain_drop[0], rain_drop[1]), (rain_drop[0] + slant, rain_drop[1] + int(round(self.drop_length * rand))), drop_color, int(round(self.drop_width * rand))) image = cv2.blur(image, self.blurr) return convertToPILImg(image, normilized=False)
def center_of_mass(image): threshold = thresh # Convert image to gray and blur it src_gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY) src_gray = cv.blur(src_gray, (3, 3)) # Edge detection canny_output = cv.Canny(src_gray, threshold, threshold * 2) contours, _ = cv.findContours(canny_output, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE) # For every found contour we now apply approximation to polygons with accuracy +-3 and stating that the curve must be closed. # After that we find a bounding rect for every polygon and save it to boundRect. # At last we find a minimum enclosing circle for every polygon and save it to center and radius vectors. contours_poly = [None] * len(contours) boundRect = [None] * len(contours) centers = [None] * len(contours) radius = [None] * len(contours) for i, c in enumerate(contours): i = 0 contours_poly[i] = cv.approxPolyDP(c, 3, True) boundRect[i] = cv.boundingRect(contours_poly[i]) centers[i], radius[i] = cv.minEnclosingCircle(contours_poly[i]) return centers[0]
def add_white_background(mask, image): mask = cv2.blur(mask, (3, 3)) background = (mask * -1.0 + 1.0) * 255 image[:, :, :] = image[:, :, :] * mask + background return image
def changeBlur(self, img, value): """ This function will take the img image and blur values as inputs. After perform blur operation using opencv function, it returns the image img. """ kernel_size = (value + 1, value + 1) # +1 is to avoid 0 img = cv2.blur(img, kernel_size) return img
def process_image(img_hsv, blur_kernel_small=(15, 15), blur_kernel_large=(127, 127)): img_rgb = cv2.cvtColor(img_hsv, cv2.COLOR_HSV2RGB) img_shape = (img_hsv.shape[0], img_hsv.shape[1]) b_over_r = img_rgb[:, :, 0] < img_rgb[:, :, 2] b_over_g = img_rgb[:, :, 1] < img_rgb[:, :, 2] b_over_rg = np.bitwise_and(b_over_r, b_over_g) b_replace = np.max([img_rgb[:, :, 0], img_rgb[:, :, 1]], axis=0) b_suppress_img = img_rgb.copy() b_suppress_img[b_over_rg, 2] = b_replace[b_over_rg] b_suppress_img_hsv = cv2.cvtColor(b_suppress_img, cv2.COLOR_RGB2HSV) enhanced_v_img = b_suppress_img_hsv[:, :, 2] # diff of Gaussian blurs img_blur_1 = cv2.blur(enhanced_v_img, blur_kernel_small) img_blur_2 = cv2.blur(enhanced_v_img, blur_kernel_large) tmp_img_1 = img_blur_1.astype(np.int16) tmp_img_2 = img_blur_2.astype(np.int16) edge_mask = tmp_img_2 - tmp_img_1 edge_mask[edge_mask > 0] = 0 edge_mask[edge_mask < 0] = 255 edge_mask = edge_mask.astype(np.uint8) contours = cv2x.filter_contours_by_size(edge_mask, min_size=63 * 63) edge_mask = np.zeros(img_shape, dtype=np.uint8) cv2.drawContours(edge_mask, contours, -1, 255, -1) # dilate just a bit edge_mask = cv2.dilate(edge_mask, (3, 3), iterations=blur_kernel_small[0]) # get black mask as black can never be a "signal" # TODO: should 'holes' mask color be configurable? will it always be black? black_mask = color_utils.create_color_mask(img_hsv, colors=['black']) edge_mask = np.bitwise_and(edge_mask, ~black_mask) return b_suppress_img_hsv, edge_mask, black_mask
def imageSmoothingImg(self): try: img = cv2.imread(self.filename) blur = cv2.blur(img, (5, 5)) cv2.imwrite('img/dist/blur.png', blur, [cv2.IMWRITE_JPEG_QUALITY, 100]) cv2.waitKey(0) cv2.destroyAllWindows() except: pass
def tune_thresholds(vid_feed, thresholds): """DOCSTRING""" # initialize window win = 'Adjustment Control Panel' cv2.namedWindow(win) # initialize variables and trackbars thresh_names = ['H_LO', 'H_HI', 'S_LO', 'S_HI', 'V_LO', 'V_HI'] blur_k_name = 'BLUR \'K\'' max_vals = [179, 179, 255, 255, 255, 255] for thresh, val, max_val in zip(thresh_names, thresholds, max_vals): cv2.createTrackbar(thresh, win, val, max_val, empty_callback) cv2.createTrackbar(blur_k_name, win, cf['blur_k']['initial'], cf['blur_k']['max'], empty_callback) cv2.setTrackbarMin(blur_k_name, win, 1) thresh_vals = None keypress = -1 while keypress == -1: __, frame = vid_feed.read() # blur frame blur_k = cv2.getTrackbarPos(blur_k_name, win) frame_blur = cv2.blur(frame, (blur_k, blur_k)) frame_hsv = cv2.cvtColor(frame_blur, cv2.COLOR_BGR2HSV) thresh_vals = np.asarray([cv2.getTrackbarPos(name, win) for name in thresh_names]) frame_thresh = cv2.inRange(frame_hsv, thresh_vals[::2], thresh_vals[1::2]) # cv2.imshow(win_thresh, frame_thresh) cv2.imshow(win, frame_thresh) keypress = cv2.waitKey(5) cv2.destroyWindow(win) vid_feed.release() return thresh_vals, keypress
def add_white_background(mask, image): """Draws a white background on the image by the given mask. mask: [height, width, depth] of type float. Full image-size binary mask. image: [height, width, depth] of type float. The image to check. Returns the image of same size with whitened background. """ mask = cv2.blur(mask, (3, 3)) background = (mask * -1.0 + 1.0) * 255 image[:, :, :] = image[:, :, :] * mask + background return image
def process_image(img_hsv): img_rgb = cv2.cvtColor(img_hsv, cv2.COLOR_HSV2RGB) img_shape = (img_hsv.shape[0], img_hsv.shape[1]) b_over_r = img_rgb[:, :, 0] < img_rgb[:, :, 2] b_over_g = img_rgb[:, :, 1] < img_rgb[:, :, 2] b_over_rg = np.bitwise_and(b_over_r, b_over_g) b_replace = np.max([img_rgb[:, :, 0], img_rgb[:, :, 1]], axis=0) b_suppress_img = img_rgb.copy() b_suppress_img[b_over_rg, 2] = b_replace[b_over_rg] b_suppress_img_hsv = cv2.cvtColor(b_suppress_img, cv2.COLOR_RGB2HSV) enhanced_v_img = b_suppress_img_hsv[:, :, 2] # diff of gaussians img_blur_1 = cv2.blur(enhanced_v_img, (15, 15)) img_blur_2 = cv2.blur(enhanced_v_img, (127, 127)) tmp_img_1 = img_blur_1.astype(np.int16) tmp_img_2 = img_blur_2.astype(np.int16) edge_mask = tmp_img_2 - tmp_img_1 edge_mask[edge_mask > 0] = 0 edge_mask[edge_mask < 0] = 255 edge_mask = edge_mask.astype(np.uint8) contours = cv2x.filter_contours_by_size(edge_mask, min_size=15 * 15) edge_mask = np.zeros(img_shape, dtype=np.uint8) cv2.drawContours(edge_mask, contours, -1, 255, -1) edge_mask = cv2.dilate(edge_mask, cross_strel, iterations=1) return b_suppress_img, edge_mask
def bgSubtractor(image, bgSubtractor): blur = cv2.blur(image, (2, 2)) #blur = cv2.blur(image,(10,10)) subtracted_image = bgSubtractor.apply(blur, learningRate=0) subtracted_image = cv2.morphologyEx(subtracted_image, cv2.MORPH_OPEN, np.ones((4, 4)), iterations=2) subtracted_image = cv2.morphologyEx(subtracted_image, cv2.MORPH_CLOSE, np.ones((4, 4)), iterations=4) return cv2.bitwise_and(image, image, mask=subtracted_image), subtracted_image
def Achar_objetos(imgX): #Função para encontrar objetos na imagem, no caso os objetos serão a malha do JOGO > # < e os caracteres utilizados no jogo > X < e > O < #img_menor = Arrumar_img(imgX) #Diminui o tamanho da imagem na função apresentada anteriormente img_menor = imgX #Passo 1: Conversão para tons de cinza imgXX = cv2.cvtColor(img_menor, cv2.COLOR_BGR2GRAY) #Passo 2: Blur/Suavização da imagem suave = cv2.blur(imgXX, (9, 9)) #A suavização da iamgem pode ser maior, mudando seus parâmetros para 5,5 / 7,7 / 9,9 ... Mas 3,3 já foi o sufuciente nos testes # suave = imgXX.copy() #Passo 3: Binarização resultando em pixels brancos e pretos #A imagem que será binarizada está em tons de cinza, assim tem apenas uma variável de cor, sendo que quando mais próximo de 0, mais preto e quanto mais próximo de 255, mais branco bin = suave.copy() #Copia a imagem suavizada bin[bin > 100] = 255 #Pixels a cima de 100 são transformados em completamente brancos bin[bin < 60] = 0 #Pixels a baixo de 60 são transformados em completamente pretos #esses valores de 100 e 60 podem variar de acordo com a imagem e iluminação do ambiente, então testes sãop encessários para encontrar os melhores valores. bin = cv2.bitwise_not(bin) # aplica as mudanças e inverte a imagem #Passo 4: Detecção de bordas com Canny bordas = cv2.Canny(bin, 70, 150) #Nessa linha, as bordas dos objetos brancos em um fundo preto são detectadas #Passo 5: Identificação e contagem dos contornos da imagem #OBS: Apenas bordas externas a um desenho são contadas e identificadas, isso para que as bordas internas ao "O" sejam ignoradas # então o quadrado central da malha do jogo deve ser aberto em um ponto, para que o que estiver dentro dele possa ser detectado # O parâmetro responsável apenas pela identificação da borda externa dos objetos é o >> cv2.RETR_EXTERNAL (objetos, lx) = cv2.findContours(bordas.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE ) #A variável lx (lixo) recebe dados que não são utilizados #A váriável objetos armazena um vetor, esse vetor tem o número de objetos como seu número de endereços, então a função len(objetos) retorna o número de objetos encontrados #Porem esse não é um vetor siples e sim um vetor multidimencional, cada endereço contem as coordenadas de cada ponto necessário para formar o contorno do objeto #isso será utilizado mais a frente para a itentificação do tamanho do objeto e se é um "X" , "O" ou a malha "#" #Toda a parte a baixo que está comentada, abre uma janela mostrando todas as etapas do tratamento de imagem e os contornos identificados #Caso queira ver, descomente as linhas, mas para que o código flua e o jogo possa ser jogado, elas devem ser comentadas #escreve(imgXX, "Imagem em tons de cinza", 0) #escreve(suave, "Suavizacao com Blur", 0) #escreve(bin, "Binarizacao com Metodo Otsu", 255) #escreve(bordas, "Detector de bordas Canny", 255) #temp = np.vstack([np.hstack([imgXX, suave]),np.hstack([bin, bordas])]) #cv2.imshow("Quantidade de objetos: "+str(len(objetos)), temp) #cv2.waitKey(0) return objetos #retorna os objetos encontraos
def callback(self, data): global count try: img = self.bridge.imgmsg_to_cv2(data, desired_encoding="bgr8") if img.dtype == 'float32': img = np.array(img) * 255 img = np.uint8(img) img = cv2.blur(img, (5, 5)) img, _, _, _, _ = combined_thresh(img) #_, _, img = combined_thresh_canny(img) #img, _, _, _ = perspective_transform(img) cv2.imshow("Image window", img.astype(np.float32)) count += 1 k = cv2.waitKey(1) if k == 113: #q cv2.imwrite("saves/" + str(count) + "_igvcw.png", img) if k == 27: #esc cv2.destroyAllWindows() try: ret = line_fit(img) left_fit = ret['left_fit'] right_fit = ret['right_fit'] bottom_y = img.shape[0] - 1 bottom_x_left = left_fit[0] * ( bottom_y**2) + left_fit[1] * bottom_y + left_fit[2] bottom_x_right = right_fit[0] * ( bottom_y**2) + right_fit[1] * bottom_y + right_fit[2] vehicle_offset = img.shape[1] / 2 - (bottom_x_left + bottom_x_right) / 2 # if 350 < bottom_x_right - bottom_x_left < 600 : # self.pub.publish(0.0) # return 0 xm_per_pix = 3.7 / 680 # meters per pixel in x dimension vehicle_offset = vehicle_offset * xm_per_pix self.pub.publish(vehicle_offset) # cross track error except TypeError: print("No lanes found.") self.pub.publish(0.0) #label_str = 'Vehicle offset from lane center: %.3f m' % self.vehicle_offset #img = cv2.putText(img, label_str, (30,70), 0, 1, (255,0,0), 2, cv2.LINE_AA) except CvBridgeError as e: print(e)
def __blur(src, type, radius): """Softens an image using one of several filters. Args: src: The source mat (numpy.ndarray). type: The blurType to perform represented as an int. radius: The radius for the blur as a float. Returns: A numpy.ndarray that has been blurred. """ if (type is BlurType.Box_Blur): ksize = int(2 * round(radius) + 1) return cv2.blur(src, (ksize, ksize)) elif (type is BlurType.Gaussian_Blur): ksize = int(6 * round(radius) + 1) return cv2.GaussianBlur(src, (ksize, ksize), round(radius)) elif (type is BlurType.Median_Filter): ksize = int(2 * round(radius) + 1) return cv2.medianBlur(src, ksize) else: return cv2.bilateralFilter(src, -1, round(radius), round(radius))
def add_rain(image, rain_drops=1500, drop_length=20, drop_width=2, blurr=(7, 7), color=(150, 150, 150)): image.load() image = np.asarray(image, dtype="int32") imshape = image.shape slant_extreme = 5 slant = np.random.randint(-slant_extreme, slant_extreme) drop_color = color rain_drops = generate_random_lines(imshape, slant, drop_length, rain_drops) for rain_drop in rain_drops: cv2.line(image, (rain_drop[0], rain_drop[1]), (rain_drop[0] + slant, rain_drop[1] + drop_length), drop_color, drop_width) image = cv2.blur(image, blurr) return convertToPILImg(image, normilized=False)
def run(self, initialisationPeriod, args): t1 = float(args.thr1) t2 = float(args.thr2) assert t1 < t2 alpha = 0.99 beta = 0.99 self.initialiseFilters(initialisationPeriod) video = cv2.VideoWriter('analyzed.avi', cv2.VideoWriter_fourcc(*'FMP4'), 15, (255, 255)) while self.stream.more() is True: self.iVAR = np.sqrt(self.iVARsq) THRESHOLD_ONE, THRESHOLD_TWO = self.updateThresholds( t1, t2, self.iVAR) frame, iCOR = self.loadVideoFrame() cv2.imshow("INPUT", frame) update, freeze = self.generateMasks(iCOR, self.iBG, THRESHOLD_ONE) self.predict_iBG(alpha, iCOR, self.iBG, update, freeze) self.predict_iVAR(beta, self.iVARsq, self.iBG, iCOR, update, freeze) output = self.generateOutputMask(THRESHOLD_TWO, self.iBG, iCOR) removed_singles = cv2.erode(output, self.kernel, iterations=1) filled_mask = cv2.dilate(removed_singles, self.kernel, iterations=2) output = cv2.blur(filled_mask, (9, 9)) self.display_mask(output) video.write(output) video.release()
def generate_color_contours(img_hsv, blur_kernel=(9, 9), mask=None, min_size=None, max_size=None, colors=('green', 'cyan', 'red', 'violet', 'yellow')): img_shape = (img_hsv.shape[0], img_hsv.shape[1]) tmp_color_img = cv2.cvtColor(img_hsv, cv2.COLOR_HSV2RGB) tmp_color_img = cv2.blur(tmp_color_img, blur_kernel) tmp_color_img = cv2.cvtColor(tmp_color_img, cv2.COLOR_RGB2HSV) color_mask = color_utils.create_color_mask(tmp_color_img, colors) color_mask = cv2.bitwise_and(color_mask, color_mask, mask=mask) # Next, clean up any "noise", say, ~ 5 x 5 contours = cv2x.filter_contours_by_size(color_mask, min_size=5 * 5) color_mask = np.zeros(img_shape, dtype=np.uint8) cv2.drawContours(color_mask, contours, -1, 255, -1) # do a couple dilation iterations to smooth some outside edges & connect any # adjacent cells each other color_mask = cv2.dilate(color_mask, cv2x.cross_strel, iterations=2) color_mask = cv2.erode(color_mask, cv2x.cross_strel, iterations=2) # filter remaining contours by size contours = cv2x.filter_contours_by_size(color_mask, min_size=min_size, max_size=max_size) print("%d color candidates found, kernel:" % len(contours), blur_kernel) return contours
def canny(image): gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) # converting to grayscale blur = cv2.blur(gray, (10, 5)) # blurring (averaging each pixel with neighbours) canny = cv2.Canny(blur, 10, 100) # Finding strong gradient lines return canny
def blur(img): img = cv2.blur(img, (3, 3)) return img
def OpenCV(): tello.connect() tello.streamon() frame_read = tello.get_frame_read() frame_skip = 300 #動画接続前 while True: if 0 < frame_skip: #フレームスキップ処理 frame_skip = frame_skip - 1 continue start_time = time.time() # time.time UNIX time(0:0:0)からの経過時間 img = frame_read.frame image_origin = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) #RGB convert r = image_origin[:,:,2] g = image_origin[:,:,1] b = image_origin[:,:,0] R = np.array(r).flatten() G = np.array(g).flatten() B = np.array(b).flatten() R = [x for x in R if x > 15] G = [x for x in G if x > 15] B = [x for x in B if x > 15] V1 = np.std(R) V2 = np.std(G) V3 = np.std(B) mode = sstats.mode(R)[0] mode1 = sstats.mode(G)[0] mode2 = sstats.mode(B)[0] h, w, c = image_origin.shape for y in range(0, h, 2): for x in range(0, w ,2): if mode - 4.7*V1 < image_origin[y,x,2] < mode + 4.8*V1: if mode1 - 4.8*V2 < image_origin[y,x,1] < mode1 + 4.8*V2 and mode2 - 4.8*V3 < image_origin[y,x,0] < mode2 + 4.8*V3: image_origin[y,x] = 0 image_origin[y,x+1] = 0 image_origin[y+1,x+1] = 0 else: image_origin[y,x] = 255 else: image_origin[y,x+1] = 0 image_origin[y,x] = 0 image_origin = cv2.blur(image_origin, (3, 3)) A = np.uint8(image_origin[:,:,2]) feature_params = {"maxCorners": 4, "qualityLevel": 0.5, "minDistance": 30, "blockSize": 5}#10 } #特徴点検出 # 特徴点の上限数 # 閾値 (高いほど特徴点数は減る) # 特徴点間の距離 (近すぎる点は除外) 30 p0 = cv2.goodFeaturesToTrack(A, mask=None, **feature_params) p0 = np.int0(p0) # 特徴点をプロットして可視化 if len(p0) == 4: for p in p0: #p0 x,y座標 x,y = p.ravel() #p0の要素を分解 no youso wo bunkai cv2.circle(image_origin, (x, y), 5, (0, 255, 255) , -1) x0 = p0[:,:,0].ravel() #x zahyou y0 = p0[:,:,1].ravel() #y zahyou l1 = np.sqrt((x0[0])**2+(y0[0])**2) l2 = np.sqrt((x0[1])**2+(y0[1])**2) l3 = np.sqrt((x0[2])**2+(y0[2])**2) l4 = np.sqrt((x0[3])**2+(y0[3])**2) l = [l1, l2, l3, l4] a = [0]*4 b = [0]*4 nn = [0, 1, 2, 3] for i in range(len(l)): if l[i] == min(l): a[0] = x0[i] b[0] = y0[i] s = i nn.remove(s) j=0 for j in nn: n=nn.copy() A = (b[0]-y0[j])/(a[0]-x0[j]) B = b[0] - A*a[0] n.remove(j) C = A*x0[n[0]] + B D = A*x0[n[1]] + B if C - y0[n[0]] > 0 and D - y0[n[1]] < 0: a[1] = x0[n[0]] b[1] = y0[n[0]] a[3] = x0[n[1]] b[3] = y0[n[1]] a[2] = x0[j] b[2] = y0[j] break elif C - y0[n[0]] < 0 and D - y0[n[1]] > 0: a[3] = x0[n[0]] b[3] = y0[n[0]] a[1] = x0[n[1]] b[1] = y0[n[1]] a[2] = x0[j] b[2] = y0[j] break d1 = np.sqrt((a[0]-a[1])**2+(b[0]-b[1])**2) d2 = np.sqrt((a[1]-a[2])**2+(b[1]-b[2])**2) d3 = np.sqrt((a[2]-a[3])**2+(b[2]-b[3])**2) d4 = np.sqrt((a[3]-a[0])**2+(b[3]-b[0])**2) line1 = cv2.line(image_origin,(a[0],b[0]),(a[1],b[1]),1000) line2 = cv2.line(image_origin,(a[1],b[1]),(a[2],b[2]),1000) line3 = cv2.line(image_origin,(a[2],b[2]),(a[3],b[3]),1000) line4 = cv2.line(image_origin,(a[3],b[3]),(a[0],b[0]),1000) #中点 c1 = (a[0]+a[2]) / 2 c2 = (b[0]+b[2]) / 2 c11 = int(c1) c21 = int(c2) cv2.circle(image_origin, (c11, c21), 5, (0, 255, 255) , -1) filename = 'telloimage' + str(frame) + '.jpg' cv2.imwrite(filename,image_origin) #S = cv2.countNonZero(G1) S = abs((1/2)*((a[3]-a[0])*(b[1]-b[0])-(a[1]-a[0])*(b[3]-b[0])))+abs((1/2)*((a[1]-a[2])*(b[3]-b[2])-(a[3]-a[2])*(b[1]-b[2]))) with open("S1 2021.3.10 8:19.txt", "a") as f: result = "{:.7f}\n".format(S) f.write(result) with open("d1 2021.3.10 8:19..txt", "a") as f: result = "{:.7f}\n".format(S) f.write(result) with open("d2 2021.3.10 8:19..txt", "a") as f: result = "{:.7f}\n".format(d2) f.write(result) print(S) print(d1) print(d2) cy = h / 2 cx = w / 2 data = [S,c1,c2,p0,cx,cy] return data if frame.time_base < 1.0/60: time_base = 1.0/60 #機械のエラーを判別するための基準 else: time_base = frame.time_base #フレームスキップ値を算出 frame_skip = int((time.time() - start_time) / time_base)
# if end the program if image_name == "exit": sys.exit() # reading the image img = cv2.imread(image_name) # resize the image to fit it to show in the screen img = cv2.resize(img, (0, 0), None, .75, .75) # converting the image to grayscale img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # inverting the image img_invert = cv2.bitwise_not(img_gray) # bluring or smoothing the inverted image with the kernel size (25,25) img_blur = cv2.blur(img_invert, (25, 25)) # Applying another type of blur for cheaking img_blur_2 = cv2.GaussianBlur(img_invert, (23, 23), 0) # The Dodge blend function divides the bottom layer by the inverted top layer. # This lightens the bottom layer depending on the value of the top layer. # We have the blurred image, which highlights the boldest edges. def dodgeV2(image, mask): # inverting color with 255 - ... return cv2.divide(image, 255 - mask, scale=256) final_img = dodgeV2(img_gray, img_blur)
def convert_blur(self): figure_size = 12 # Dimension of the x and y axis of the karnel img_blur = cv2.blur(self.img,(figure_size, figure_size)) return img_blur
from cv2 import cv2 import numpy as np img = cv2.imread('E:\opencv\sample\data\opencv-logo.png') img1 = cv2.imread('E:\opencv\sample\data\pic2.png') blur = cv2.blur(img, (7, 7)) #used for image avg blur Gblur = cv2.GaussianBlur(img, (7, 7), 1) #give gaussian blur Mblur = cv2.medianBlur(img1, 7) #gives median blur Bblur = cv2.bilateralFilter(img, 9, 75, 75) cv2.imshow('original', img) cv2.imshow('averaging image', blur) cv2.imshow('gaussian blur image', Gblur) cv2.imshow(' image1', img1) cv2.imshow('median blur image', Mblur) cv2.imshow('bilateral blur image', Bblur) cv2.waitKey(0) cv2.destroyAllWindows()
def rescaleFrame(frame, scale=0.75): width = int(frame.shape[1] * scale) height = int(frame.shape[0] * scale) dimensions = (width, height) return cv.resize(frame, dimensions, interpolation=cv.INTER_AREA) init = cv.imread('imagen/wppstalkerlarge.jpg') img = rescaleFrame(init, 0.3) cv.imshow('stalker', img) #Averaging blur average = cv.blur(img, (3, 3)) cv.imshow('averageblur', average) #Gaussian blur gauss = cv.GaussianBlur(img, (3, 3), 0) cv.imshow('gaussianBlur', gauss) #Median Blur (good for Computer Vision) medianBlur = cv.medianBlur(img, 3) cv.imshow('medianBlur', medianBlur) #Bilateral Blur (good as well for Computer Vision) biBlur = cv.bilateralFilter(img, 10, 35, 25) cv.imshow('bilateralBlur', biBlur) cv.waitKey(0)
import cv2.cv2 as cv import numpy as np import matplotlib.pyplot as plt img = cv.imread("imgs/sap.png") img = cv.cvtColor(img, cv.COLOR_BGR2RGB) kernel = np.ones((5, 5), np.float32) / 25 dst = cv.filter2D(img, -1, kernel) blur = cv.blur(img, (5, 5)) gauss = cv.GaussianBlur(img, (5, 5), 0) median = cv.medianBlur(img, 5) bilatera = cv.bilateralFilter(img, 9, 75, 75) titles = [ 'original image', '2D convolution', 'blur', 'Gaussian', 'Median blur', 'Bilatera filter' ] image = [img, dst, blur, gauss, median, bilatera] for i in range(len(titles)): plt.subplot(2, 3, i + 1), plt.imshow(image[i], "gray") plt.title(titles[i]) plt.xticks([]), plt.yticks([]) plt.show()
#print(preds) save_original_image_path = f"{folder}/inference_{inference_ori_img_name}.png" save_mask_image_path = f"{folder}/inference_{inference_img_name}.png" save_foreground_image_path = f"{folder}/inference_{foreground_img_namge}.png" save_background_image_path = f"{folder}/inference_{background_img_namge}.png" save_foreground_focus_image_path = f"{folder}/inference_{foreground_focus}.png" torchvision.utils.save_image(preds, save_mask_image_path) torchvision.utils.save_image(aimage_path, save_original_image_path) foreground_image = segment_extraction( original_image_path=save_original_image_path, mask_image_path=save_mask_image_path, segment_image_path=save_foreground_image_path, mode='foreground', ) background_image = segment_extraction( original_image_path=save_original_image_path, mask_image_path=save_mask_image_path, segment_image_path=save_background_image_path, mode='background', ) # TODO: Smooth extracted foreground borders in saved images. foreground_focused_image = cv2.blur(background_image, ksize=(8, 8)) + foreground_image cv2.imwrite(save_foreground_focus_image_path, cv2.cvtColor(foreground_focused_image, cv2.COLOR_RGB2BGR))
from cv2 import cv2 import numpy as np img = cv2.imread("frank.jpg") a = cv2.blur(img, (10, 10)) g = cv2.GaussianBlur(img, (5, 5), 0) m = cv2.medianBlur(img, 5) cv2.imshow("o", img) cv2.imshow("a", a) cv2.imshow("g", g) cv2.imshow("m", m) cv2.waitKey(0) cv2.destroyAllWindows()
def blur_demo(image, aver_blur=(4, 4)): h = np.random.randint(1, aver_blur[0]) w = np.random.randint(1, aver_blur[1]) dst = cv.blur(image, (w, h)) #cv.imshow('blur_demo',dst) return dst