def frame_diff(prev_frame, cur_frame, next_frame): # Difference between the current frame and the next frame diff_frames_1 = cv.absdiff(next_frame, cur_frame) # Difference between the current frame and the previous frame diff_frames_2 = cv.absdiff(cur_frame, prev_frame) return cv.bitwise_and(diff_frames_1, diff_frames_2)
def getClosestPlayerByIcon(image, icons, background_bgr): empty_icon = numpy.full_like(image, background_bgr[0]) empty_icon[:,:,1] = numpy.full((image.shape[0], image.shape[1]), background_bgr[1]) empty_icon[:,:,2] = numpy.full((image.shape[0], image.shape[1]), background_bgr[2]) distances = [numpy.sum(cv2.absdiff(empty_icon, image))] for i in range(len(icons)): character_distances = [] for j in range(len(icons[i])): curr_icon = addBackground(icons[i][j], background_bgr) character_distances.append(numpy.sum(cv2.absdiff(curr_icon, image))) distances.append(numpy.min(character_distances)) return numpy.argmin(distances) - 1
def frame_diff(prev_frame, cur_frame, next_frame): diff_frames_1 = cv.absdiff( next_frame, cur_frame ) # absdiff(src1, src2), src는 array or scalar, absdiff는 absoulute diffent로 절대값을 비교 diff_frames_2 = cv.absdiff(cur_frame, prev_frame) return_diff = cv.absdiff(diff_frames_1, diff_frames_2) threshold = len( return_diff[np.where(return_diff > 2)] ) # np.where is return elements chosen from x or y depending on condition if threshold > 500: print('threshold > 200 : ', threshold) return return_diff, diff_frames_1
def frame_diff(prev_frame, cur_frame, next_frame): # Difference between the current frame and the next frame diff_frames_1 = cv.absdiff(next_frame, cur_frame) # Difference between the current frame and the previous frame diff_frames_2 = cv.absdiff(cur_frame, prev_frame) # return_diff = cv.bitwise_and(diff_frames_1, diff_frames_2) return_diff = cv.absdiff(diff_frames_1, diff_frames_2) threshold = len(return_diff[np.where(return_diff > 2)]) if threshold > 500: print('threshold > 200 : ', threshold) return return_diff
def detect(self, image, tVal=25): # compute the absolute difference between the background model # and the image passed in, then threshold the delta image delta = cv2.absdiff(self.bg.astype("uint8"), image) thresh = cv2.threshold(delta, tVal, 255, cv2.THRESH_BINARY)[1] # perform a series of erosions and dilations to remove small # blobs thresh = cv2.erode(thresh, None, iterations=2) thresh = cv2.dilate(thresh, None, iterations=2) # find contours in the thresholded image and initialize the # minimum and maximum bounding box regions for motion cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts) (minX, minY) = (np.inf, np.inf) (maxX, maxY) = (-np.inf, -np.inf) # if no contours were found, return None if len(cnts) == 0: return None # otherwise, loop over the contours for c in cnts: # compute the bounding box of the contour and use it to # update the minimum and maximum bounding box regions (x, y, w, h) = cv2.boundingRect(c) (minX, minY) = (min(minX, x), min(minY, y)) (maxX, maxY) = (max(maxX, x + w), max(maxY, y + h)) # otherwise, return a tuple of the thresholded image along # with bounding box return (thresh, (minX, minY, maxX, maxY))
def _get_diff_rc_color( self, examined_img_index: int, possibilities: List[int]) -> Tuple[int, int, np.array, np.array]: """ pick a random image from <possibilities> that is different than <examined_img>, compare those two images and return a random coordinate where they have different colors. The color of <examed_img> at that coordinate. :param examined_img_index: the index of the examined image in self._possible_images :param possibilities: a list of indexes of the compared images :return: row, col, color, color """ that_index = -1 for possibility in possibilities: if possibility != examined_img_index: that_index = possibility assert that_index != -1 this_img = self._possible_images[examined_img_index] that_img = self._possible_images[that_index] absolute_diff = cv2.absdiff(this_img, that_img) mask = np.any(absolute_diff != [0, 0, 0], axis=-1) nonzero_r_c = np.where(mask) # if not np.any(nonzero_r_c): # cv2.imshow('this', this_img) # cv2.imshow('that', that_img) # cv2.waitKey() # cv2.destroyAllWindows() assert np.any(nonzero_r_c), "Got identical images" diff_r, diff_c = nonzero_r_c[0][0], nonzero_r_c[1][0] this_color = this_img[diff_r][diff_c] that_color = that_img[diff_r][diff_c] return diff_r, diff_c, this_color, that_color
def pixel_difference(imgA: Image, imgB: Image, threshold: int = 0) -> float: height, width, _ = imgA.shape diffImg = cv2.absdiff(imgA, imgB) diffImg = cv2.cvtColor(diffImg, cv2.COLOR_BGR2GRAY) _, diffImg = cv2.threshold(diffImg, threshold, 255, cv2.THRESH_BINARY) numDiffPixels = cv2.countNonZero(diffImg) return numDiffPixels / (width * height)
def transform(self, filename: str): self.initialize_video(filename) if (self.every is not None): new_idx = range(self.n_frames)[::self.every] elif (self.hertz is not None): interval = self.fps / float(self.hertz) new_idx = np.arange(0, self.n_frames, interval).astype(int) new_idx = list(new_idx) elif self.top_n is not None: diffs = [] for i, img in enumerate(range(self.n_frames)): if i == 0: last = img continue pixel_diffs = cv2.sumElems( cv2.absdiff(self.get_frame(last), self.get_frame(img))) diffs.append(sum(pixel_diffs)) last = img new_idx = sorted(range(len(diffs)), key=lambda i: diffs[i], reverse=True)[:self.top_n] result = [] for index in new_idx: result.append(self.get_frame(index)) return result
def detect_contours(self, frame, firstFrame): gray = self.preprocess(frame) frameDelta = cv2.absdiff(firstFrame, gray) thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1] thresh = cv2.dilate(thresh, None, iterations=2) cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) return imutils.grab_contours(cnts)
def getClosestCharacterByCloseup(image, character_closeups, mask, background_bgr): distances = [] for i in range(len(character_closeups)): character_distances = [] for j in range(8): curr_closeup = addBackground(character_closeups[i][j], background_bgr) character_distances.append(numpy.sum(numpy.multiply(cv2.absdiff(curr_closeup, image), mask))) distances.append(numpy.min(character_distances)) return numpy.argmin(distances)
def get_images_diff(frames_path: str, image_list: list, idx: int): img1 = cv2.imread(os.path.join(frames_path, image_list[idx]), 0) img2 = cv2.imread(os.path.join(frames_path, image_list[idx + 1]), 0) # --- take the absolute difference of the images --- res = cv2.absdiff(img1, img2) # --- convert the result to integer type --- res = res.astype(numpy.uint32) # --- find percentage difference based on number of pixels that are not zero --- return (numpy.count_nonzero(res) * 100) / res.size
def diff(img1: np.ndarray, img2: np.ndarray) -> np.ndarray: """ difference between two images to detect changes over time Args: img1: image as numpy array img2: image as numpy array Returns: combined image """ return cv2.absdiff(img1, img2)
def CompareFrames(self, prevFrame, frame): frameDelta = cv2.absdiff(self.compareFrame, frame) thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1] thresh = cv2.dilate(thresh, None, iterations=2) boxes = self.GetBoxes(thresh) for box in boxes: cv2.rectangle(frame, (box.x, box.y), (box.x + box.w, box.y + box.h), (0, 255, 0), 2) return (frameDelta, thresh, boxes)
def callback(self, data): try: cv_image = self.bridge.imgmsg_to_cv2(data, "bgr8") except CvBridgeError as e: print(e) # (rows, cols, channels) = cv_image.shape # if cols > 60 and rows > 60: # cv2.circle(cv_image, (50, 50), 10, 255) # cv2.imshow("Image window", cv_image) # cv2.waitKey(3) if (self.set_s == 0): self.prev_cv_image = cv_image.copy() self.set_s = 1 binary = cv_image.copy() # print("Here Once") curr_gray = cv2.cvtColor(cv_image, cv2.COLOR_BGR2GRAY) prev_gray = cv2.cvtColor(self.prev_cv_image, cv2.COLOR_BGR2GRAY) frame_diff = cv2.absdiff(curr_gray, prev_gray) ret, thresh = cv2.threshold(frame_diff, 30, 255, cv2.THRESH_BINARY) kernel = np.ones((3, 3), np.uint8) dilated = cv2.dilate(thresh, kernel, iterations=1) cnts = cv2.findContours(dilated.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts) ctemp_c = cv_image.copy() valid_cntr = [] for c in cnts: #(x, y, w, h) = cv2.boundingRect(c) M = cv2.moments(c) self.cX = int(M["m10"] / M["m00"]) self.cY = int(M["m01"] / M["m00"]) cv2.drawContours(ctemp_c, cnts, -1, (127, 200, 0), 2) cv2.circle(ctemp_c, (self.cX, self.cY), 7, (255, 255, 255), -1) print("center", self.cX, self.cY) # Detect blobs(groups of pixels) # image = self.DetectBlobs(morphed, cv_image) # Detect groups using countour area (Green formula) cv2.imshow("Image window", cv_image) cv2.imshow('frame diff ', frame_diff) cv2.imshow("contour", ctemp_c) cv2.waitKey(1) self.prev_cv_image = cv_image.copy()
def segment(image): global bg global number_of_frames_threshold diff = cv2.absdiff(bg.astype("uint8"), image) threshold_image = cv2.threshold(diff, number_of_frames_threshold, 255, cv2.THRESH_BINARY)[1] contours, hierarchy = cv2.findContours(threshold_image.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) if len(contours) == 0: return else: segmented_image = max(contours, key=cv2.contourArea) return (threshold_image, segmented_image)
def change(self, image, mode=0, gaussian=5, valve=100): ''' mode return 0 带阀值限制后的输出 1 未使用阀值过滤的原始差异结果 2 带边框指示变化区域的原始图 gaussian 高斯模糊的程度 valve 过滤阀值 ''' # 创建参数解析器并解析参数 ap = argparse.ArgumentParser() ap.add_argument("-v", "--video", help="path to the video file") ap.add_argument("-a", "--min-area", type=int, default=500, help="minimum area size") args = vars(ap.parse_args()) # 高斯模糊,防噪点 image = cv2.GaussianBlur(image, (gaussian, gaussian), 0) # 计算当前帧和第一帧的不同 frameDelta = cv2.absdiff(self.__init_frame, image) thresh = cv2.threshold(frameDelta, valve, 255, cv2.THRESH_BINARY)[1] if mode == 0: #cv2.imshow("Thresh", thresh) return thresh elif mode == 1: #cv2.imshow("Frame Delta", frameDelta) return frameDelta elif mode == 2: # 创建边框 (cnts, _) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for c in cnts: if cv2.contourArea(c) < args["min_area"]: continue (x, y, w, h) = cv2.boundingRect(c) cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2) # 输出带矩形标记的当前帧 cv2.imshow("Security Feed", image) return image else: raise (ValueError)
def frame_diff(self): _, self.previous_frame = self.video_capture.read() while (True): _, self.current_frame = self.video_capture.read() # compute the absolute difference between the current frame and previous frame # convert it to grayscale, and blur it diff = cv2.absdiff(self.previous_frame, self.current_frame) gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray, (self.kernel_size, self.kernel_size), 0) _, thresh = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY) # dilate the thresholded image to fill in holes, then find contours on thresholded image dilated = cv2.dilate(thresh, None, iterations=3) contours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) movement_flag = False for contour in contours: if cv2.contourArea(contour) < self.min_area: continue movement_flag = True show_frame = np.copy(self.current_frame) if self.lot_of_noise_det: white_pixels_count = np.sum(dilated) if not movement_flag and white_pixels_count < self.mov_detected_pixels_threshold: self.mark_as_removed(show_frame) else: self.video_writer.write(self.current_frame) else: if not movement_flag: self.mark_as_removed(show_frame) else: self.video_writer.write(self.current_frame) # cv2.imshow("Live Contours", self.previous_frame) cv2.drawContours(show_frame, contours, -1, (0, 255, 0), 2) cv2.imshow("Live Feed", show_frame) cv2.imshow("Dilated", dilated) cv2.imshow("Frame Delta", gray) self.previous_frame = self.current_frame if cv2.waitKey(60) & 0xFF == ord('q'): break
def Shadow_removal(warped): # Funkcija za otklanjanje sjene sa slike img = warped.copy() # Kopiramo poravnatu sliku pod imenom img rgb_planes = cv2.split(img) # Razdvajamo boje RGB spektruma result_norm_planes = [] # Niz u koji spremamo normalizirane boje slike # Prolazimo kroz sve dijelove boja slike for plane in rgb_planes: dilated_img = cv2.dilate(plane, np.ones((7,7), np.uint8)) # bg_img = cv2.medianBlur(dilated_img, 21) # Prolazimo kroz sve 3 boje RGB-a, te diff_img = 255 - cv2.absdiff(plane, bg_img) # Normaliziramo svaku boju kako bi otklonili sjenu norm_img = cv2.normalize(diff_img,None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8UC1) # result_norm_planes.append(norm_img) # Spremamo narmaliziranu boju u niz result_norm = cv2.merge(result_norm_planes) # Ponovno spajamo sve boje u jednu sliku result_norm = cv2.cvtColor(result_norm, cv2.COLOR_BGR2GRAY) # Pretvaramo sliku u crno-bijelu cv2.imwrite('scanned.jpg', result_norm) # Spremamo sliku kojoj smo otklonili sjenu
def ImageSegmentation(frame, count): # path is the video directory for which we are applying the segementation # any motion box of less than this size will be a noise #(assumption, to not consider, light changes as motion) min_size_area = 50 cv2.imshow("frame", frame) frame_number = count # if the frame could not be grabbed, then we have reached the end # of the video if frame is None: print("Frame not readed or frame read ends") return 0 # resize the frame, convert it to grayscale, and blur it frame = imutils.resize(frame, width=500) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray, (21, 21), 0) # must be odd # if the first frame is None, initialize it if compFrame is None: compFrame = gray return 0 # compute the absolute difference between the current frame and # first frame frameDelta = cv2.absdiff(compFrame, gray) if frame_number-prevUpdateCounter == 10: compFrame = prevFrame prevUpdateCounter = frame_number prevFrame = gray return 0 prevFrame = gray thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1] # dilate the thresholded image to fill in holes, then find contours # on thresholded image thresh = cv2.dilate(thresh, None, iterations=2) cnts = cv2.findContours( thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts) temp = 0 # loop over the contours for c in cnts: if cv2.contourArea(c) < min_size_area: continue temp = 1 if temp == 1: bounding_boxes.append(frame_number) return 1 return 0
def find_license(img): ''' 预处理函数 ''' m = 400 * img.shape[0] / img.shape[1] img = cv2.resize(img, (400, int(m)), interpolation=cv2.INTER_CUBIC) # BGR转换为灰度图像 gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 灰度拉伸 stretchedimg = stretch(gray_img) r = 16 h = w = r * 2 + 1 kernel = np.zeros((h, w), np.uint8) cv2.circle(kernel, (r, r), r, 1, -1) # 开运算 openingimg = cv2.morphologyEx(stretchedimg, cv2.MORPH_OPEN, kernel) # 获取差分图,两幅图像做差 cv2.absdiff('图像1','图像2') strtimg = cv2.absdiff(stretchedimg, openingimg) # 图像二值化 binaryimg = dobinaryzation(strtimg) # canny边缘检测 canny = cv2.Canny(binaryimg, binaryimg.shape[0], binaryimg.shape[1]) # 进行闭运算 kernel = np.ones((5, 19), np.uint8) closingimg = cv2.morphologyEx(canny, cv2.MORPH_CLOSE, kernel) # 进行开运算 openingimg = cv2.morphologyEx(closingimg, cv2.MORPH_OPEN, kernel) # 再次进行开运算 kernel = np.ones((11, 5), np.uint8) openingimg = cv2.morphologyEx(openingimg, cv2.MORPH_OPEN, kernel) # 消除小区域,定位车牌位置 rect = locate_license(openingimg, img) return rect, img
def preprocessor(img): gray = img dilated_gray = cv2.dilate(gray, np.ones((7, 7), np.uint8)) bg_gray = cv2.medianBlur(dilated_gray, 21) diff_gray = 255 - cv2.absdiff(gray, bg_gray) norm_gray = diff_gray.copy() norm_img = np.zeros((320, 240)) norm_gray = cv2.normalize(diff_gray, norm_img, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8UC1) test_img = diff_gray - norm_gray test_img2 = cv2.dilate(test_img, np.ones((5, 5))) ret2, gray3 = cv2.threshold(test_img2, 0, 255, cv2.THRESH_OTSU) gray3 = cv2.resize(gray3, (28, 28), interpolation=cv2.INTER_AREA) return gray3, gray3.copy()
def segment(image, threshold=50): global bg # find the absolute difference between background and current frame diff = cv2.absdiff(bg.astype("uint8"), image) # threshold the diff image so that we get the foreground ret, thresholded = cv2.threshold(diff, threshold, 255, cv2.THRESH_BINARY) # get the contours in the thresholded image cnts, _ = cv2.findContours(thresholded.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # return None, if no contours detected if len(cnts) == 0: return else: # based on contour area, get the maximum contour which is the hand segmented = max(cnts, key=cv2.contourArea) return (thresholded, segmented)
def car(frame1, frame2): diff = cv2.absdiff(frame1, frame2) gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray, (5, 5), 0) _, thresh = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY) dilated = cv2.dilate(thresh, None, iterations=3) contours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) for contour in contours: (x, y, w, h) = cv2.boundingRect(contour) if cv2.contourArea(contour) < 900: continue cv2.rectangle(frame1, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.putText(frame1, "Status: {}".format('Movement'), (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 3) #cv2.drawContours(frame1,contours, -1, (0,255,0),2) return frame1
def preprocessor2(img): gray = img dilated_gray = cv2.dilate(gray, np.ones((7, 7), np.uint8)) bg_gray = cv2.medianBlur(dilated_gray, 21) diff_gray = 255 - cv2.absdiff(gray, bg_gray) norm_gray = diff_gray.copy() _, thr_gray = cv2.threshold(norm_gray, 253, 0, cv2.THRESH_TRUNC) norm_img = np.zeros((320, 240)) norm_gray = cv2.normalize(diff_gray, norm_img, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8UC1) test_img = diff_gray - norm_gray test_img2 = cv2.dilate(test_img, np.ones((5, 5))) ret2, gray3 = cv2.threshold(test_img2, 40, 255, cv2.THRESH_OTSU) gray3 = cv2.resize(gray3, (28, 28), interpolation=cv2.INTER_AREA) ret3, gray4 = cv2.threshold(test_img2, 40, 255, cv2.THRESH_TRUNC) gray4 = cv2.resize(gray4, (28, 28), interpolation=cv2.INTER_AREA) gray5 = cv2.resize(thr_gray, (28, 28), interpolation=cv2.INTER_AREA) _, gray6 = cv2.threshold(norm_gray, 30, 30, cv2.THRESH_OTSU) #gray6 = cv2.resize(gray6, (28,28), interpolation=cv2.INTER_AREA) #gray6 = cv2.resize(thr_gray, (28,28), interpolation=cv2.INTER_AREA) #(ret6, gray6) = cv2.threshold(test_img2, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) #gray6 = cv2.resize(norm_gray, (28,28), interpolation=cv2.INTER_AREA) #gray = cv2.adaptiveThreshold(gray1, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 5, 3) #(thresh, gray2) = cv2.threshold(gray1, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) return gray3, gray4, gray5, gray6
def getEffectiveFrame(videopath,dirfile): # 如果文件目录不存在则创建目录 if not os.path.exists(dirfile): os.makedirs(dirfile) (filepath, tempfilename) = os.path.split(videopath)#分离路径和文件名 (filename, extension) = os.path.splitext(tempfilename)#区分文件的名字和后缀 #Setting fixed threshold criteria设置固定阈值标准 USE_THRESH = False #fixed threshold value固定阈值 THRESH = 0.6 #Setting fixed threshold criteria设置固定阈值标准 USE_TOP_ORDER = False #Setting local maxima criteria设置局部最大值标准 USE_LOCAL_MAXIMA = True #Number of top sorted frames排名最高的帧数 NUM_TOP_FRAMES = 50 #smoothing window size平滑窗口大小 len_window = int(50) print("target video :" + videopath) print("frame save directory: " + dirfile) # load video and compute diff between frames加载视频并计算帧之间的差异 cap = cv2.VideoCapture(str(videopath)) curr_frame = None prev_frame = None frame_diffs = [] frames = [] success, frame = cap.read() i = 0 while(success): luv = cv2.cvtColor(frame, cv2.COLOR_BGR2LUV) curr_frame = luv if curr_frame is not None and prev_frame is not None: #logic here diff = cv2.absdiff(curr_frame, prev_frame)#获取差分图 diff_sum = np.sum(diff) diff_sum_mean = diff_sum / (diff.shape[0] * diff.shape[1])#平均帧 frame_diffs.append(diff_sum_mean) frame = Frame(i, diff_sum_mean) frames.append(frame) prev_frame = curr_frame i = i + 1 success, frame = cap.read() cap.release() # compute keyframe keyframe_id_set = set() if USE_TOP_ORDER: # sort the list in descending order以降序对列表进行排序 frames.sort(key=operator.attrgetter("diff"), reverse=True)# 排序operator.attrgetter for keyframe in frames[:NUM_TOP_FRAMES]: keyframe_id_set.add(keyframe.id) if USE_THRESH: print("Using Threshold")#使用阈值 for i in range(1, len(frames)): if (rel_change(np.float(frames[i - 1].diff), np.float(frames[i].diff)) >= THRESH): keyframe_id_set.add(frames[i].id) if USE_LOCAL_MAXIMA: print("Using Local Maxima")#使用局部极大值 diff_array = np.array(frame_diffs) sm_diff_array = smooth(diff_array, len_window)#平滑 frame_indexes = np.asarray(argrelextrema(sm_diff_array, np.greater))[0]#找极值 for i in frame_indexes: keyframe_id_set.add(frames[i - 1].id)# 记录极值帧数 plt.figure(figsize=(40, 20)) plt.locator_params("x", nbins = 100) # stem 绘制离散函数,polt是连续函数 plt.stem(sm_diff_array,linefmt='-',markerfmt='o',basefmt='--',label='sm_diff_array') plt.savefig(dirfile + filename+'_plot.png') # save all keyframes as image将所有关键帧另存为图像 cap = cv2.VideoCapture(str(videopath)) curr_frame = None keyframes = [] success, frame = cap.read() idx = 0 while(success): if idx in keyframe_id_set: name = filename+'_' + str(idx) + ".jpg" cv2.imwrite(dirfile + name, frame) keyframe_id_set.remove(idx) idx = idx + 1 success, frame = cap.read() cap.release()
# Captura de movimento from cv2 import cv2 import numpy as np cap = cv2.VideoCapture('vtest.avi') ret, frame1 = cap.read() ret, frame2 = cap.read() while cap.isOpened(): diff = cv2.absdiff(frame1, frame2) gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray, (5, 5), 0) _, thresh = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY) dilated = cv2.dilate(thresh, None, iterations=3) contours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) for contour in contours: (x, y, w, h) = cv2.boundingRect(contour) if cv2.contourArea(contour) < 900: continue cv2.rectangle(frame1, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.putText(frame1, f"Status: {'Movement'}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2) #cv2.drawContours(frame1, contours, -1, (0, 255, 0), 2) cv2.imshow("feed", frame1) frame1 = frame2 ret, frame2 = cap.read()
def getClosestLanguageType(image, languages): distances = [] for i in range(len(languages)): distances.append(numpy.sum(cv2.absdiff(languages[i][0], image))) index = numpy.argmin(distances) return languages[index][1]
def getClosestDigit(image, digit_images): distances = [] for i in range(len(digit_images)): distances.append(numpy.sum(cv2.absdiff(digit_images[i], image))) digit = numpy.argmin(distances) return digit - 1
static_mask = previous continue (grabbed, frame) = camera.read() frame = imutils.resize(frame, width=700) clone = frame.copy() (height, width) = frame.shape[:2] #potential speedup if converted to grayscale, the net should intake grayscale as well grayClone = cv2.cvtColor(clone, cv2.COLOR_BGR2GRAY) # Calculate absolute difference of current frame and # the next frame _diff = cv2.absdiff(grayClone, previous) num_diff = cv2.countNonZero(_diff) # Calculate the minimum nonzero pixels in order to update the background if min_diff is None: min_diff = np.min(num_diff) continue min_diff = np.min( num_diff) if min_diff > np.min(num_diff) else min_diff if num_diff > min_diff: # gives coordinates in (x,y) format. Note that, row = x and column = y. # mask = cv2.findNonZero(_diff) # rows = 79844; cols = 1 # pix_mask[tuple(mask.T)] = 0
def frame_diff(prev_frame, cur_frame): diff_frames = absdiff(prev_frame, cur_frame) diff_frames_with_cv = cv2.absdiff(prev_frame, cur_frame) final = np.hstack((cur_frame, diff_frames, diff_frames_with_cv)) cv2.imshow('diff', final)