我们从Python开源项目中,提取了以下13个代码示例,用于说明如何使用cv2.countNonZero()。
def cv2_ELA(name): input_image = cv2.imread(name) scale = 15 quality = 75 cv2.imwrite(base+'ELA/temp.jpg', input_image, [cv2.IMWRITE_JPEG_QUALITY, quality]) compressed_image = cv2.imread(base+'ELA/temp.jpg') output_image = (input_image - compressed_image) * scale gray_image = cv2.cvtColor(output_image, cv2.COLOR_BGR2GRAY) nonzero = cv2.countNonZero(gray_image) total = output_image.shape[0] * output_image.shape[1] zero = total - nonzero ratio = zero * 100 / float(total) cv2.imwrite(base+'ELA/results/{}_results.png'.format(name), output_image) return ratio, output_image
def get_current_page(self, img): img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) area = crop_image(img, **self.predefined.page_area) area = mask_image([254], [255], area) height, width = area.shape current_page = 0 for x in range(4): box = crop_image(area, (x * width / 4), 0, ((x + 1) * width / 4), height) if cv2.countNonZero(box) > 0: current_page = x break return current_page + 1
def check_if_battle(self, img): img = np.array(img) img = img[750:800, 0:400] blue_min = np.array([250, 250, 250], np.uint8) blue_max = np.array([255, 255, 255], np.uint8) amount = cv2.inRange(img, blue_min, blue_max) if cv2.countNonZero(amount) > (50 * 200): return True return False
def process_image(self, cv_image, header, tag): """ process the image """ hsv = cv2.cvtColor(cv_image, cv2.COLOR_BGR2HSV) # mask for color range if self.color_range: mask = cv2.inRange(hsv, self.color_range[0], self.color_range[1]) count = cv2.countNonZero(mask) if count: kernel = np.ones((5, 5), np.uint8) mask = cv2.dilate(mask, kernel, iterations=2) contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) for i, c in enumerate(contours): x, y, w, h = cv2.boundingRect(c) if self.prefix is not None: name = '{0}{1}_{2}_{3}.png'.format(self.prefix, tag, header.seq, i) print name roi = cv_image[y:y+h, x:x+w] gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY) gray = cv2.equalizeHist(gray) cv2.imwrite(name, gray) for c in contours: x, y, w, h = cv2.boundingRect(c) cv2.rectangle(cv_image, (x, y), (x+w, y+h), (0, 255, 0)) elif self.prefix is not None: name = '{0}Negative_{1}_{2}.png'.format(self.prefix, tag, header.seq, ) cv2.imwrite(name, cv_image) cv2.namedWindow(tag, cv2.WINDOW_NORMAL) cv2.resizeWindow(tag, 600, 600) cv2.imshow(tag, cv_image) cv2.waitKey(1)
def recognize_card(original_image, country='kg', preview=False): from processing.border_removal import resize from processing.crop import process_image result = [] cropped_image = "croped-image.jpg" process_image(original_image, cropped_image) idcard = cv2.imread(cropped_image, cv2.COLOR_BGR2GRAY) idcard = resize(idcard, width=720) scale_down = (8 * 170 / detect_dpi(idcard)) if scale_down <= 4: rows, cols = idcard.shape[:2] idcard = cv2.resize(idcard, (scale_down * cols / 8, scale_down * rows / 8)) contours, hierarchy = recognize_text(idcard) for index, contour in enumerate(contours): [x, y, w, h] = cv2.boundingRect(contour) gray = cv2.cvtColor(idcard, cv2.COLOR_RGB2GRAY) roi = gray[y:y + h, x:x + w] if cv2.countNonZero(roi) / h * w > 0.55: if h > 16 and w > 16: filename = '%s.jpg' % index cv2.imwrite(filename, roi) text = pytesseract.image_to_string( Image.open(filename), lang="kir+eng", config="-psm 7" ) item = {'x': x, 'y': y, 'w': w, 'h': h, 'text': text} result.append(item) cv2.rectangle(idcard, (x, y), (x + w, y + h), (255, 0, 255), 2) if preview: original_image = original_image.split('/')[-1] location = save_image('regions' + original_image, idcard) return location, regionskir(result) return regionskir(result)
def getDarkColorPercent(image): height = np.size(image, 0) width = np.size(image, 1) imgSize = width * height result = cv2.threshold(image, 100, -1, cv2.THRESH_TOZERO)[1] nonzero = cv2.countNonZero(result) if nonzero > 0: return (imgSize - nonzero) / float(imgSize) else: return 0 # ???????
def motion_detection(t_minus, t_now, t_plus): delta_view = delta_images(t_minus, t_now, t_plus) retval, delta_view = cv2.threshold(delta_view, 16, 255, 3) cv2.normalize(delta_view, delta_view, 0, 255, cv2.NORM_MINMAX) img_count_view = cv2.cvtColor(delta_view, cv2.COLOR_RGB2GRAY) delta_count = cv2.countNonZero(img_count_view) dst = cv2.addWeighted(screen,1.0, delta_view,0.6,0) delta_count_last = delta_count return delta_count
def skeletonize(image, size, structuring=cv2.MORPH_RECT): # determine the area (i.e. total number of pixels in the image), # initialize the output skeletonized image, and construct the # morphological structuring element area = image.shape[0] * image.shape[1] skeleton = np.zeros(image.shape, dtype="uint8") elem = cv2.getStructuringElement(structuring, size) # keep looping until the erosions remove all pixels from the # image while True: # erode and dilate the image using the structuring element eroded = cv2.erode(image, elem) temp = cv2.dilate(eroded, elem) # subtract the temporary image from the original, eroded # image, then take the bitwise 'or' between the skeleton # and the temporary image temp = cv2.subtract(image, temp) skeleton = cv2.bitwise_or(skeleton, temp) image = eroded.copy() # if there are no more 'white' pixels in the image, then # break from the loop if area == area - cv2.countNonZero(image): break # return the skeletonized image return skeleton
def detection(self, hsv_image): """Check for detection in the image """ mask = cv2.inRange(hsv_image, self.color_low, self.color_high) if self.baseline_cnt > 0: nmask = cv2.bitwise_not(mask) if self.baseline is None: rospy.loginfo("getting baseline for {}".format(self.name)) self.baseline = nmask else: self.baseline = cv2.bitwise_or(nmask, self.baseline) mask = cv2.bitwise_and(mask, self.baseline) count = cv2.countNonZero(mask) + self.baseline_fuzzy self.low_count = max(self.low_count, count) self.high_count = self.low_count + self.baseline_fuzzy self.baseline_cnt -= 1 return elif self.baseline is not None: mask = cv2.bitwise_and(mask, self.baseline) count = cv2.countNonZero(mask) if count > self.low_count and self.active is None: self.active = rospy.get_rostime() rospy.loginfo("{} ACTIVE ({})".format(self.name, count)) self.cloud.reset() if self.callbacks[0] is not None: self.callbacks[0](self.name) elif self.active is not None and count < self.high_count: rospy.loginfo("{} GONE ({})".format(self.name, count)) self.cloud.reset() self.active = None if self.callbacks[2] is not None: self.published = False self.report_count = 0 if self.callbacks[1] is not None: self.callbacks[1](self.name) # DEBUGGING to see what the masked image for the request is if self.debug: cv2.namedWindow(self.name, cv2.WINDOW_NORMAL) if self.baseline is not None: cv2.namedWindow(self.name+'_baseline', cv2.WINDOW_NORMAL) cv2.imshow(self.name+'_baseline', self.baseline) cv2.imshow(self.name, mask) cv2.waitKey(1) # to to see if we notify the location callback if self.is_active() and self.report_count > self.min_reports: now = rospy.get_rostime() if (self.active + self.stablize_time) < now: self.published = True point = PointStamped() center = self.cloud.find_center() point.header.seq = 1 point.header.stamp = now point.header.frame_id = self.frame_id point.point.x = center[0] point.point.y = center[1] point.point.z = center[2] if self.callbacks[2] is not None: self.callbacks[2](self.name, point)
def __findLine(self): self.__grabImage(); if(self.currentImage is None): #grabbing image failed return -2.0 #Convert to Grayscale img = cv2.cvtColor(self.currentImage, cv2.COLOR_BGR2GRAY) #Blur to reduce noise img = cv2.medianBlur(img,25) #Do Thresholding h,img = cv2.threshold(img, self.thresh, self.maxValue, cv2.THRESH_BINARY_INV) img = cv2.blur(img,(2,2)) #Make image smaller img = cv2.resize(img, (self.horizontalRes, self.verticalRes)) #org_img = cv2.resize(org_img, (self.horizontalRes, self.verticalRes)) #Create skeleton 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() zeros = size - cv2.countNonZero(img) if zeros==size: done = True #Do Line Detection lines = cv2.HoughLinesP(skel,1,np.pi/180,2, self.hough_minLineLength,self.hough_maxLineGap) #get minimum and maximum x-coordinate from lines x_min = self.horizontalRes+1.0 x_max = -1.0; if(lines != None and len(lines[0]) > 0): for x1,y1,x2,y2 in lines[0]: x_min = min(x_min, x1, x2) x_max = max(x_max, x1, x2) #cv2.line(org_img,(x1,y1),(x2,y2),(0,255,0),2) #write output visualization #cv2.imwrite("output-img.png",org_img); #find the middle point x of the line and return #return -1.0 if no lines found if(x_max == -1.0 or x_min == (self.horizontalRes+1.0) ): return -1.0 #no line found else: return (x_min + x_max) / 2.0