def base(): if request.method == 'GET': return "<h1>Crop AI</h1>" if request.method == 'POST': if 'InputImg' not in request.files: print("No file part") return redirect(request.url) file = request.files['InputImg'] if file.filename == '': print('No selected file') return redirect(request.url) if file and allowed_file(file.filename): filestr = request.files['InputImg'].read() img = cv2.imdecode(np.fromstring(filestr, np.uint8), cv2.IMREAD_COLOR) img = cv2.resize(img, (96, 96), interpolation=cv2.INTER_AREA) hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # find the green color mask_green = cv2.inRange(hsv, (36, 0, 0), (86, 255, 255)) # find the brown color mask_brown = cv2.inRange(hsv, (8, 60, 20), (145, 255, 255)) # find the yellow color in the leaf mask_yellow = cv2.inRange(hsv, (5, 42, 143), (145, 255, 255)) # find the black color in the leaf mask_black = cv2.inRange(hsv, (100, 100, 100), (127, 127, 127)) # find any of the four colors(green or brown or yellow or black) in the image mask = cv2.bitwise_or(mask_green, mask_brown) mask = cv2.bitwise_or(mask, mask_yellow) mask = cv2.bitwise_or(mask, mask_black) # Bitwise-AND mask and original image res = cv2.bitwise_and(img, img, mask=mask) # Gaussian blur with 3x3 kernel blur_img = cv2.GaussianBlur(res, (3, 3), 0) # Histogram equalization B, G, R = cv2.split(blur_img) output_R = cv2.equalizeHist(R) output_G = cv2.equalizeHist(G) output_B = cv2.equalizeHist(B) img = cv2.merge((output_R, output_G, output_B)) img = img / 255 img_array = np.expand_dims(img, axis=0) output = label_dictionary[model.predict(img_array)[0].argmax()] return output
def get_feedback_frame(): frame = queue_frames[0].copy() for i in range(1, max_frame_trace): if queue_frames[i] is not None: frame = cv2.bitwise_or(frame, queue_frames[i]) return frame
def rm_otsu_sunshade(img, roi, config): shadow = get_shadow(img, roi) img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # get threshold for shadow region # print('thr_in_shadow') thr_in_shadow = masked_otsu_threshold(img_gray, shadow) # get road markings in shadow _, rm_in_shadow = cv2.threshold(img_gray, thr_in_shadow, 255, cv2.THRESH_BINARY) # kernel_erode = np.ones((7,7), np.uint8) # shadow_eroded = cv2.erode(roi_shadow, kernel_erode) rm_in_shadow = cv2.bitwise_and(rm_in_shadow, rm_in_shadow, mask=shadow) # get threshold for sunlight region shadow_inv = cv2.bitwise_not(shadow) shadow_inv = cv2.bitwise_and(shadow_inv, shadow_inv, mask=roi) thr_out_shadow = masked_otsu_threshold(img_gray, shadow_inv) # get road markings not in shadow _, rm_out_shadow = cv2.threshold(img_gray, int( (thr_out_shadow * 1.5) % 255), 255, cv2.THRESH_BINARY) # rm_out_shadow = cv2.bitwise_and(rm_out_shadow, rm_out_shadow, mask=shadow_inv) # combine markings in shadow and not in shadow rm = cv2.bitwise_or(rm_in_shadow, rm_out_shadow) rm = cv2.bitwise_and(rm, rm, mask=roi) return rm
def logic_demo(m1, m2): dst1 = cv.bitwise_and(m1, m2) dst2 = cv.bitwise_or(m1, m2) dst3 = cv.bitwise_not(m1) cv.imshow("and", dst1) cv.imshow("or", dst2) cv.imshow("not", dst3)
def generate(self, text): plate = self.draw(text) plate = cv2.bitwise_not(plate) #黑底白字 plate = cv2.bitwise_or(plate, self.bg) #加入背景 plate = rotRandrom(plate, 15, (plate.shape[1], plate.shape[0])) plate = Add_Env(plate, self.env_path) plate = GaussBlur(plate, 1 + R(7)) return plate
def extract(img, left, right): dim_y = len(img) dim_x = len(img[0]) # cv2.imshow('', img) # cv2.waitKey(0) final_mask = np.zeros((dim_y, dim_x, 3), np.uint8) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # cv2.imshow('gray', gray) # cv2.waitKey(0) _, thresh = cv2.threshold(gray, 75, 255, cv2.THRESH_BINARY_INV) # cv2.imshow('thresh', thresh) # cv2.waitKey(0) l, r = 0, 0 t = 0 max_cnt = [] print("_____________") while r - l < right - left: t += 1 cnt = copy.deepcopy(thresh) # cv2.imshow('cnt', cnt) # cv2.waitKey(0) contours, hierarchy = cv2.findContours(cnt, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) cv2.drawContours(cnt, contours, -1, 255, t) # cv2.imshow('cnt', cnt) # cv2.waitKey(0) contours, hierarchy = cv2.findContours(cnt, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) max_cnt = max(contours, key=cv2.contourArea) # print(max_cnt) # for tmp in max_cnt: # print(tmp) l = min(max_cnt[:, :, 0]) r = max(max_cnt[:, :, 0]) # print(l, r) cv2.drawContours(final_mask, [max_cnt], 0, (255, 255, 255), -1) # cv2.imshow('final_mask', final_mask) # cv2.waitKey(0) bit_and = cv2.bitwise_and(img, final_mask) bit_not = cv2.bitwise_not(final_mask) final = cv2.bitwise_or(bit_and, bit_not) # cv2.imshow('final', final) # cv2.waitKey(0) contrast = cv2.addWeighted(final, 1.5, final, 0, 0) # cv2.imshow('contrast', contrast) # cv2.waitKey(0) return contrast
def find_contour_union(contour_list, img_shape): union_mask = np.zeros(img_shape, dtype=np.uint8) for c in contour_list: c_mask = np.zeros(img_shape, dtype=np.uint8) cv2.drawContours(c_mask, [c], 0, 255, cv2.FILLED) union_mask = cv2.bitwise_or(union_mask, c_mask) return union_mask
def Fill_Holes(image): im_fill = image.copy() h, w = image.shape[:2] mask = np.zeros((h + 2, w + 2), np.uint8) cv2.floodFill(im_fill, mask, (0, 0), 255) im_fill_inv = cv2.bitwise_not(im_fill) filled_image = cv2.bitwise_or(im_fill_inv, image) return filled_image
def thresholding(img): img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) kernel = np.ones((5, 5)) img_blur = cv.GaussianBlur(img_gray, (5, 5), 0) img_canny = cv.Canny(img_blur, 50, 100) img_close = cv.morphologyEx(img_canny, cv.MORPH_GRADIENT, np.ones((10, 10))) img_dial = cv.dilate(img_canny, kernel, iterations=1) img_erode = cv.erode(img_dial, kernel, iterations=1) img_color = color_filter(img) combined_image = cv.bitwise_or(img_color, img_erode, img_close) return combined_image, img_canny, img_color, img_close
def get_cityscapes_rm_da(img, semantics): """Applies two adaptive filters to find road markings""" semantics_road = (128, 64, 128) mask_road = cv2.inRange(semantics, semantics_road, semantics_road) # cv2.imwrite('temp/cityscapes_road_mask.png', mask_road) height = img.shape[0] width = img.shape[1] vertices = np.array([[(0, height), (0, int(height * 3 / 4)), (width, int(height * 3 / 4)), (width, height)]]) mask_bottom = np.zeros((img.shape[0], img.shape[1]), dtype=np.uint8) cv2.fillPoly(mask_bottom, vertices, 255) mask_top = cv2.bitwise_not(mask_bottom) mask_road_top = cv2.bitwise_and(mask_road, mask_road, mask=mask_top) mask_road_bottom = cv2.bitwise_and(mask_road, mask_road, mask=mask_bottom) img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # img = cv2.bitwise_and(img, img, mask=mask) thr_adaptive_top = masked_adaptive_threshold(img, mask_road_top, max_value=255, size=101, C=-15) thr_adaptive_top = cv2.convertScaleAbs(thr_adaptive_top) thr_adaptive_top = cv2.bitwise_and(thr_adaptive_top, thr_adaptive_top, mask=mask_road_top) thr_adaptive_bottom = masked_adaptive_threshold(img, mask_road_bottom, max_value=255, size=251, C=-15) thr_adaptive_bottom = cv2.convertScaleAbs(thr_adaptive_bottom) thr_adaptive_bottom = cv2.bitwise_and(thr_adaptive_bottom, thr_adaptive_bottom, mask=mask_road_bottom) thr_adaptive_combined = cv2.bitwise_or(thr_adaptive_top, thr_adaptive_bottom) plt.figure() plt.subplot(3, 1, 1) plt.imshow(img, cmap='gray') plt.subplot(3, 1, 2) plt.imshow(thr_adaptive_top, cmap='gray') plt.subplot(3, 1, 3) plt.imshow(thr_adaptive_bottom, cmap='gray') return thr_adaptive_combined
def _filter_red(self, frame): hsv_img = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) frame_threshed1 = cv2.inRange(hsv_img, self._LOWER_RED_MIN, self._LOWER_RED_MAX) frame_threshed2 = cv2.inRange(hsv_img, self._UPPER_RED_MIN, self._UPPER_RED_MAX) frame_threshed_red = cv2.bitwise_or(frame_threshed1, frame_threshed2) # close gaps in red objects kernel = np.ones((5, 5), np.uint8) frame_threshed_red = cv2.morphologyEx(frame_threshed_red, cv2.MORPH_CLOSE, kernel) frame_threshed_red = cv2.bitwise_not(frame_threshed_red) return frame_threshed_red
def main(): image = cv2.imread('test.jpg') height, width = image.shape[:2] zone = [(0, height), (0, 230), (300, 100), (640, 240), (width, height)] # Only work with this image focused_img = focus_zone(image, np.array([zone], np.int32)) focused_img[100:, :] = line_detection_non_vectorized(focused_img[100:, :]) result = cv2.bitwise_or( image, focused_img) # Take all pixel where isnt black between 2 imgs plt.imshow(result) plt.show()
def sample(im, extractor, sample_points=None, num_points=50, r=20): """ Sample uniformly at random num_points samples with radius r and feature vector v=(f1, f2,...,fn) :param im: The image to sample :param extractor: The feature extractor to use :param sample_points: A pre-sampled set of points to use :param num_points: The number of points to sample :param r: The radius of each point :return: list[point_x, point_y, r, f1, f2,...,fn] """ # radius must be an integer r = int(r) w = im.shape[1] h = im.shape[0] # The masking stuff is just to make the sample a circle with radius r mask = np.zeros([2 * r, 2 * r], dtype=np.uint8) mask = cv.circle(mask, (int(mask.shape[1] / 2), int(mask.shape[0] / 2) + 1), r + 1, color=(255, 255, 255), thickness=-1) mask[mask == 0] = 1 points = [] for i in range(num_points): if sample_points is not None: pt = np.array(sample_points[i]) else: pt = np.array( [np.random.randint(r, w - r), np.random.randint(r, h - r)]) t = im[pt[1] - r:pt[1] + r, pt[0] - r:pt[0] + r] try: masked_img = cv.bitwise_or(t, t, mask=mask) except: print("ERROR: pt={}, r={}".format(pt, r)) continue class_prob = extractor.extract(masked_img, r) points.append([pt[0], pt[1], r, *class_prob]) return np.array(points)
def Skeletons(imgSrc: np.ndarray, kernel: np.ndarray) -> np.ndarray: K = 0 Zeros = np.zeros(imgSrc.shape, dtype=np.uint8) imgTmp = imgSrc while True: imgTmp = Erode(imgTmp, kernel) if (imgTmp == Zeros).all(): break K += 1 imgDst = np.zeros(imgSrc.shape, dtype=np.uint8) for i in range(K): imgErode = Erode(imgSrc, kernel, i + 1) imgDst = cv.bitwise_or( imgErode - Dilate(Erode(imgErode, kernel), kernel), imgDst) return imgDst
def detect_edge(image): """ Args: image: (numpy.ndarray) Returns: detected_img: (numpy.ndarray) """ detected_img = None sobel_x = cv2.Sobel(image, ddepth=cv2.CV_64F, dx=1, dy=0) sobel_y = cv2.Sobel(image, ddepth=cv2.CV_64F, dx=0, dy=1) sobel_x = numpy.uint8(numpy.absolute(sobel_x)) sobel_y = numpy.uint8(numpy.absolute(sobel_y)) detected_img = cv2.bitwise_or(sobel_x, sobel_y) return detected_img
def img_calc(img1, img2, method): if method == "add": return cv.add(img1, img2) elif method == "sub": return cv.subtract(img1, img2) elif method == "multi": return cv.multiply(img1, img2) elif method == "divide": return cv.divide(img1, img2) elif method == "and": return cv.bitwise_and(img1, img2) elif method == "or": return cv.bitwise_or(img1, img2) elif method == "not": return cv.bitwise_not(img1, img2) else: return False
def pig_filter(image_name, face_data_points): cap = cv2.VideoCapture(0) detector = dlib.get_frontal_face_detector() nose_image = cv2.imread(image_name) predictor = dlib.shape_predictor(face_data_points) while (True): # Capture frame-by-frame _, frame = cap.read() frame = cv2.flip(frame, 1) gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = detector(frame) for face in faces: landmarks = predictor(gray_frame, face) top_nose = (landmarks.part(29).x, landmarks.part(29).y) center_nose = (landmarks.part(30).x, landmarks.part(30).y) left_nose = (landmarks.part(31).x, landmarks.part(31).y) right_nose = (landmarks.part(35).x, landmarks.part(35).y) nose_width = int( hypot(left_nose[0] - right_nose[0], left_nose[1] - right_nose[1]) * 1.2) nose_height = int(nose_width * 0.77) nose_pig = cv2.resize(nose_image, (nose_width, nose_height)) top_left = (int(center_nose[0] - nose_width / 2), int(center_nose[1] - nose_height / 2)) bottom_right = (int(center_nose[0] + nose_width / 2), int(center_nose[1] + nose_height / 2)) nose_area = frame[top_left[1]:top_left[1] + nose_height, top_left[0]:top_left[0] + nose_width] nose_pig_gray = cv2.cvtColor(nose_pig, cv2.COLOR_BGR2GRAY) _, nose_mask = cv2.threshold(nose_pig_gray, 25, 255, cv2.THRESH_BINARY_INV) nose_area_no_nose = cv2.bitwise_and(nose_area, nose_area, mask=nose_mask) nose_final = cv2.bitwise_or(nose_area_no_nose, nose_pig) frame[top_left[1]:top_left[1] + nose_height, top_left[0]:top_left[0] + nose_width] = nose_final cv2.imshow("frame", frame) if cv2.waitKey(1) & 0xFF == ord('q'): break # When everything done, release the capture cap.release() cv2.destroyAllWindows()
def skeletize(img): size = np.size(img) skel = np.zeros(img.shape, np.uint8) element = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3)) done = False while not done: eroded = cv2.erode(img, element) temp = cv2.dilate(eroded, element) temp = cv2.subtract(img, temp) skel = cv2.bitwise_or(skel, temp) img = eroded.copy() zeroes = size - cv2.countNonZero(img) if zeroes == size: done = True return skel
def polygen_overlap(polygen1, polygen2, mode='iou', shape=(1333, 1333)): assert mode in ['iou', 'iof'] polygen1 = np.array(polygen1, dtype=np.int32).reshape(-1, 2) polygen2 = np.array(polygen2, dtype=np.int32).reshape(-1, 2) im1 = np.zeros(shape, dtype="uint8") im2 = np.zeros(shape, dtype="uint8") mask1 = cv.fillPoly(im1, polygen1, 255) mask2 = cv.fillPoly(im2, polygen2, 255) masked_and = cv.bitwise_and(mask1, mask2, mask=im1) masked_or = cv.bitwise_or(mask1, mask2) # or_area = np.sum(np.float32(np.greater(masked_or, 0))) and_area = np.sum(np.float32(np.greater(masked_and, 0))) if mode == 'iou': union = np.sum(np.float32(np.greater(masked_or, 0))) else: union = np.sum(np.float32(mask1)) iou = and_area / union return iou
def edge_detection(): img = cv2.imread('2.jpg', cv2.IMREAD_GRAYSCALE) lap = cv2.Laplacian(img, cv2.CV_64F, ksize=3) lap = np.uint8(np.absolute(lap)) sobelX = cv2.Sobel(img, cv2.CV_64F, 1, 0) sobelY = cv2.Sobel(img, cv2.CV_64F, 0, 1) sobelX = np.uint8(np.absolute(sobelX)) sobelY = np.uint8(np.absolute(sobelY)) sobelCombined = cv2.bitwise_or(sobelX, sobelY) titles = ['image', 'Laplacian', 'sobelX', 'sobelY', 'sobelCombined'] images = [img, lap, sobelX, sobelY, sobelCombined] for i in range(5): plt.subplot(2, 3, i + 1), plt.imshow(images[i], 'gray') plt.title(titles[i]) plt.xticks([]), plt.yticks([]) plt.show()
def Detection(image,parameters_dict): image=cv2.resize(image,(640,480)) #cv2.imshow("normal",image) ogimg=image#store the image given as a parameter for later bitwise and operation image=cv2.cvtColor(image, cv2.COLOR_BGR2HSV) image=cv2.GaussianBlur(image, (17, 17), 2) lower=np.array([parameters_dict["hue"][0],parameters_dict["sat"][0],parameters_dict["value"][0]]) higher=np.array([parameters_dict["hue"][1],parameters_dict["sat"][1],parameters_dict["value"][1]]) mask=cv2.inRange(image,lower,higher) if parameters_dict["OR_MASK"]==True: lower_oran=np.array([175,100,100],dtype="uint8") higher_oran=np.array([179,255,255],dtype="uint8") mask1=cv2.inRange(image,lower_oran,higher_oran) mask=cv2.bitwise_or(mask,mask1) if parameters_dict["Kernel"]==True: Kernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3)) else: Kernel=cv2.getStructuringElement(cv2.MORPH_RECT,(5,5)) Thresholded_img=cv2.bitwise_and(ogimg,ogimg,mask=mask) filtered_img=cv2.morphologyEx(Thresholded_img,cv2.MORPH_OPEN,Kernel) return filtered_img
def ConvexHull(imgSrc: np.ndarray) -> np.ndarray: # 注:此方法很难收敛,还是用Graham扫描法好一点 # 凸包的四个hit结构元 kernel = [ np.array([[1, 0, 0], [1, 0, 0], [1, 0, 0]], dtype=np.uint8), np.array([[1, 1, 1], [0, 0, 0], [0, 0, 0]], dtype=np.uint8), np.array([[0, 0, 1], [0, 0, 1], [0, 0, 1]], dtype=np.uint8), np.array([[0, 0, 0], [0, 0, 0], [1, 1, 1]], dtype=np.uint8) ] # 凸包的四个miss结构元 kernelInv = [ np.array([[0, 0, 0], [0, 1, 0], [0, 0, 0]], dtype=np.uint8), np.array([[0, 0, 0], [0, 1, 0], [0, 0, 0]], dtype=np.uint8), np.array([[0, 0, 0], [0, 1, 0], [0, 0, 0]], dtype=np.uint8), np.array([[0, 0, 0], [0, 1, 0], [0, 0, 0]], dtype=np.uint8) ] imgDst = np.zeros(imgSrc.shape, dtype=np.uint8) h, w = imgSrc.shape for i in range(4): imgRes1 = imgSrc counter = 0 while True: imgRes2 = MyHitMiss(imgRes1, kernel[i], kernelInv[i]) flag = bool(True) for y in range(h): for x in range(w): r = max(imgRes2[y, x], imgSrc[y, x]) imgRes2[y, x] = r if r != imgRes1[y, x]: flag = False # 因为太难收敛了,来个阈值限制下 if flag or counter > 3: imgDst = cv.bitwise_or(imgDst, imgRes2) break imgRes1 = imgRes2 counter += 1 return imgDst
import numpy as np from cv2 import cv2 #Create 300*300 numpy array and 250*250 white rectangle inside it rectangle = np.zeros((300, 300), dtype="uint8") cv2.rectangle(rectangle, (25, 25), (275, 275), 255, -1) cv2.imshow("rectangle", rectangle) #Create 300*300 numpy array and 150 radius white circle inside it circle = np.zeros((300, 300), dtype="uint8") cv2.circle(circle, (150, 150), 150, 255, -1) cv2.imshow("circle", circle) # performing the bitwise oprations bitwiseAnd = cv2.bitwise_and(rectangle, circle) cv2.imshow("AND", bitwiseAnd) cv2.waitKey(0) bitwiseOr = cv2.bitwise_or(rectangle, circle) cv2.imshow("OR", bitwiseOr) cv2.waitKey(0) bitwiseXor = cv2.bitwise_xor(rectangle, circle) cv2.imshow("XOR", bitwiseXor) cv2.waitKey(0) bitwiseNot = cv2.bitwise_not(rectangle, circle) cv2.imshow("Not", bitwiseNot) cv2.waitKey(0)
def paste_signature(img, signature): h, w = img.shape signature = resize(signature) img[h - 150:, w - 150:] = cv2.bitwise_or(img[h - 150:, w - 150:], signature)
def mark_lanes(image): if image is None: raise ValueError("no image given to mark_lanes") # grayscale the image to make finding gradients clearer gray = cv2.cvtColor(image,cv2.COLOR_RGB2GRAY) gray = cv2.equalizeHist(gray) #hsv img_hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) lower_yellow = np.array([10, 43, 46], dtype = "uint8") #20,100,100 #26 upper_yellow = np.array([29, 255, 255], dtype="uint8") #20.255.255 #34 mask_yellow = cv2.inRange(img_hsv, lower_yellow, upper_yellow) mask_white = cv2.inRange(gray, 200, 255) mask_yw = cv2.bitwise_or(mask_white, mask_yellow) mask_yw_image = cv2.bitwise_and(gray, mask_yw) kernel_size = 5 gauss_gray = gaussian_blur(mask_yw_image,kernel_size) # Define a kernel size and apply Gaussian smoothing kernel_size = 5 blur_gray = cv2.GaussianBlur(gray,(kernel_size, kernel_size), 0) # Define our parameters for Canny and apply low_threshold = 30 high_threshold = 150 # edges_img = cv2.Canny(np.uint8(blur_gray), low_threshold, high_threshold) #old blur_gray gray image edges_img = cv2.Canny(np.uint8(gauss_gray), low_threshold, high_threshold) #hsv image #print(" edges_img height:",edges_img.shape[0]) #print(" edges_img width:",edges_img.shape[1]) imshape = image.shape vertices = np.array([[(0, imshape[0]), (620, 410), #[620,410] (imshape[1], imshape[0]) ]], dtype=np.int32) #vertices = np.array([[(0+200, imshape[0]),(620, 410),(643, 410),(imshape[1]-300, imshape[0]),(imshape[1]-500, imshape[0]), # (543, 510),(720, 510),(0+400, imshape[0])]],dtype=np.int32) # 3 #left_bottom = [0, edges_img.shape[0]] #right_bottom = [edges_img.shape[1], edges_img.shape[0]] #apex = [edges_img.shape[1]/2, 410] #vertices = np.array([ left_bottom, right_bottom, apex ], np.int32) masked_edges = region_of_interest(edges_img, vertices) # Define the Hough transform parameters rho = 2 # distance resolution in pixels of the Hough grid theta = np.pi/180 # angular resolution in radians of the Hough grid threshold = 30 # minimum number of votes (intersections in Hough grid cell) min_line_length = 150 # minimum number of pixels making up a line max_line_gap = 500 # maximum gap in pixels between connectable line segments line_image = hough_lines(image, masked_edges, rho, theta, threshold, min_line_length, max_line_gap) # Draw the lines on the image # initial_img * alpha + img * β + λ lines_edges = cv2.addWeighted(image, 0.8, line_image, 1, 0) return mask_yellow, mask_white, mask_yw, mask_yw_image, blur_gray, edges_img, masked_edges, line_image, lines_edges
backg = cv2.imread("backg.jpg") backg = cv2.resize(backg, (1024, 768), interpolation=cv2.INTER_LINEAR_EXACT) while True: ret, frame = cap.read() frame = cv2.flip(frame, 1) frame = cv2.resize(frame, (1024, 768), interpolation=cv2.INTER_LINEAR_EXACT) cv2.namedWindow('magic') cv2.setMouseCallback('magic', draw_function) if (clicked): lower_bound = np.array([h - 20, s - 50, v - 50]) upper_bound = np.array([h + 20, s + 70, v + 70]) clicked = False blur = cv2.GaussianBlur(frame, (5, 5), 0) hsv_frame = cv2.cvtColor(blur, cv2.COLOR_BGR2HSV) # cv2.imshow("hsv_frame",hsv_image) mask = cv2.inRange(hsv_frame, lower_bound, upper_bound) #mask=cv2.morphologyEx(mask,cv2.MORPH_OPEN,(7,7)) mask_inv = (255 - mask) filtered = cv2.bitwise_and(backg, backg, mask=mask) magic = cv2.bitwise_or(frame, filtered, mask=mask_inv) final = magic + filtered # final=cv2.resize(final,(1024,768),interpolation=cv2.INTER_LINEAR_EXACT) #cv2.imshow("orignal",frame) cv2.imshow("magic", final) #cv2.imshow("mask",mask) #cv2.imshow("filter",filtered) if cv2.waitKey(1) == 13: break cap.release() cv2.destroyAllWindows()
from cv2 import cv2 as cv import numpy as np blank = np.zeros((400, 400), dtype='uint8') rectangle = cv.rectangle(blank.copy(), (30, 30), (370, 370), 255, -1) circle = cv.circle(blank.copy(), (200, 200), 200, 255, -1) cv.imshow('Rectangle', rectangle) cv.imshow('Circle', circle) #bitwise AND. Exactly what you imagine bitwiseAND = cv.bitwise_and(rectangle, circle) cv.imshow('bitWiseAND', bitwiseAND) #bitwise OR bitwiseOR = cv.bitwise_or(rectangle, circle) cv.imshow('bitWiseOR', bitwiseOR) #bitwise XOR bitwiseXOR = cv.bitwise_xor(rectangle, circle) cv.imshow('bitwiseXOR', bitwiseXOR) #bitwise NOT bitwiseNOT = cv.bitwise_not(bitwiseXOR) cv.imshow('bitwisenot', bitwiseNOT) cv.waitKey(0)
from cv2 import cv2 import numpy as np img1 = cv2.imread("bib.png") img2 = cv2.imread("ml.png") bit_and = cv2.bitwise_and(img2, img1) bit_or = cv2.bitwise_or(img2, img1) bit_xor = cv2.bitwise_xor(img1, img2) bit_not = cv2.bitwise_not(img1) bit_not2 = cv2.bitwise_not(img2) cv2.imshow("img1", img1) cv2.imshow("img2", img2) cv2.imshow("bit_and", bit_and) cv2.imshow("bit_or", bit_or) cv2.imshow("bit_xor", bit_xor) cv2.imshow("bit_not", bit_not) cv2.imshow("bit_not2", bit_not2) cv2.waitKey(0)
totalSettingCaptures += 1 for i in range(0, 3): averageHSV[i] = (totalSettingCaptures - 1) * averageHSV[i] + targetPoint[i] averageHSV[i] /= totalSettingCaptures if averageOfrecentHSV[i] < minHSV[i]: minHSV[i] = averageOfrecentHSV[i] if averageOfrecentHSV[i] > maxHSV[i]: maxHSV[i] = averageOfrecentHSV[i] # Making the Final Frame image to display if notification != '': frame = numpy.zeros((frameHeight, frameWidth), numpy.uint8) cv2.putText(frame, notification, (20, 40), cv2.FONT_HERSHEY_PLAIN, 3, (0, 255, 255), 2) else: maskFrame = cv2.inRange(frameHSV, minHSV, maxHSV) invertedMaskFrame = cv2.bitwise_not(maskFrame) negetiveMaskedFrame = cv2.bitwise_not(frame, mask=maskFrame) frameWithoutMaskedPart = cv2.bitwise_and(frame, frame, mask=invertedMaskFrame) frame = cv2.bitwise_or(negetiveMaskedFrame, frameWithoutMaskedPart) cv2.imshow('Video', frame) cv2.destroyAllWindows() videoCaptured.release()
from cv2 import cv2 as cv import numpy as np img = cv.imread('Photos/cat.jpg') cv.imshow('Cat', img) gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) cv.imshow('Gray', gray) # Laplacian lap = cv.Laplacian(gray, cv.CV_64F) lap = np.uint8(np.absolute(lap)) cv.imshow('Laplacian', lap) # Sobel sobelx = cv.Sobel(gray, cv.CV_64F, 1, 0) sobely = cv.Sobel(gray, cv.CV_64F, 0, 1) combined_sobel = cv.bitwise_or(sobelx, sobely) cv.imshow('Sobel X', sobelx) cv.imshow('Sobel Y', sobely) cv.imshow('Combined Sobel', combined_sobel) canny = cv.Canny(gray, 150, 175) cv.imshow('Canny', canny) cv.waitKey(0)