我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用cv2.IMREAD_COLOR。
def __convertImagetoBlackWhite(self): self.Image = cv.imread(self.ImagePath, cv.IMREAD_COLOR) self.imageOriginal = self.Image if self.Image is None: print 'some problem with the image' else: print 'Image Loaded' self.Image = cv.cvtColor(self.Image, cv.COLOR_BGR2GRAY) self.Image = cv.adaptiveThreshold( self.Image, 255, # Value to assign cv.ADAPTIVE_THRESH_MEAN_C,# Mean threshold cv.THRESH_BINARY, 11, # Block size of small area 2, # Const to substract ) return self.Image
def updateImage(self, img): arr = self.bridge.imgmsg_to_cv2(img,"bgr8") # Uncomment following two lines for CompressedImage topic #np_arr = np.fromstring(img.data, np.uint8) #arr = cv2.imdecode(np_arr, cv2.IMREAD_COLOR) if self.image_lock.acquire(True): self.img = arr if self.model is None: self.model = self.get_model() self.img_out, self.boxes = self.predict(self.model, self.img) self.img_out = np.asarray(self.img_out[0,:,:,:]) for box in self.boxes: if 'traffic light' in box['label']: cv2.rectangle(self.img_out,(box['topleft']['x'], box['topleft']['y']), (box['bottomright']['x'], box['bottomright']['y']), (255,0,0), 6) cv2.putText(self.img_out, box['label'], (box['topleft']['x'], box['topleft']['y'] - 12), 0, 0.6, (255,0,0) ,6//3) print(self.img_out.shape) self.image_lock.release()
def get_data(datadir): #datadir = args.data # assume each image is 512x256 split to left and right imgs = glob.glob(os.path.join(datadir, '*.jpg')) data_X = np.zeros((len(imgs),3,img_cols,img_rows)) data_Y = np.zeros((len(imgs),3,img_cols,img_rows)) i = 0 for file in imgs: img = cv2.imread(file,cv2.IMREAD_COLOR) img = cv2.resize(img, (img_cols*2, img_rows)) #print('{} {},{}'.format(i,np.shape(img)[0],np.shape(img)[1])) img = np.swapaxes(img,0,2) X, Y = split_input(img) data_X[i,:,:,:] = X data_Y[i,:,:,:] = Y i = i+1 return data_X, data_Y
def check_image(name): expected_data = json.loads(open('./img/' + name + '.json').read()) if not expected_data['enabled']: return expected_targets = expected_data['targets'] img = cv2.imread('./img/' + name + '.jpg', cv2.IMREAD_COLOR) hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) args = config.copy() args['img'] = hsv args['output_images'] = {} actual_targets = find(**args) # make sure same number of targets are detected assert len(expected_targets) == len(actual_targets) # targets is a list of 2-tuples with expected and actual results targets = zip(expected_targets, actual_targets) # compare all the different features of targets to make sure they match for pair in targets: expected, actual = pair # make sure that the targets are close to where they are supposed to be assert is_close(expected['pos']['x'], actual['pos']['x'], 0.02) assert is_close(expected['pos']['y'], actual['pos']['y'], 0.02) # make sure that the targets are close to the size they are supposed to be assert is_close(expected['size']['width'], actual['size']['width'], 0.02) assert is_close(expected['size']['height'], actual['size']['height'], 0.02)
def get_example(self, i): np.random.seed(None) idA = self.trainAkey[np.random.randint(0,len(self.trainAkey))] idB = self.trainBkey[np.random.randint(0,len(self.trainBkey))] #print(idA) imgA = cv2.imread(idA, cv2.IMREAD_COLOR) imgB = cv2.imread(idB, cv2.IMREAD_COLOR) imgA = self.do_augmentation(imgA) imgB = self.do_augmentation(imgB) imgA = self.preprocess_image(imgA) imgB = self.preprocess_image(imgB) return imgA, imgB
def _load_data(self, data_id): imgpath = osp.join( self.data_dir, 'img/{}.jpg'.format(data_id)) seg_imgpath = osp.join( self.data_dir, 'cls/{}.mat'.format(data_id)) ins_imgpath = osp.join( self.data_dir, 'inst/{}.mat'.format(data_id)) img = cv2.imread(imgpath, cv2.IMREAD_COLOR) img = img.transpose((2, 0, 1)) mat = scipy.io.loadmat(seg_imgpath) seg_img = mat['GTcls'][0]['Segmentation'][0].astype(np.int32) seg_img = np.array(seg_img, dtype=np.int32) seg_img[seg_img == 255] = -1 mat = scipy.io.loadmat(ins_imgpath) ins_img = mat['GTinst'][0]['Segmentation'][0].astype(np.int32) ins_img[ins_img == 255] = -1 ins_img[np.isin(seg_img, [-1, 0])] = -1 return img, seg_img, ins_img
def load_board(board_image_file_name): """ Parse the input board screenshot into a Board object. :param board_image_file_name: Path to the screenshot of the board. :return: A Board instance representing the input board. """ img = cv2.imread(board_image_file_name, cv2.IMREAD_COLOR) coordinate_map = {} for i in range(10): for j in range(10): pixel_i = IMAGE_BLOCK_START_I + i * IMAGE_BLOCK_OFFSET pixel_j = IMAGE_BLOCK_START_J + j * IMAGE_BLOCK_OFFSET bgr = img[pixel_i][pixel_j] color_code = struct.pack('BBB', *bgr).encode('hex') if color_code == 'e4eff7': coordinate_map[Coordinate(i, j)] = EmptyColor() else: coordinate_map[Coordinate(i, j)] = Color(color_code) return Board.from_coordinate_map(coordinate_map)
def load(self, filename, analyze_only): # Load image, then do various conversions and thresholding. self.img_orig = cv2.imread(filename, cv2.IMREAD_COLOR) if self.img_orig is None: raise CompilerException("File '{}' not found".format(filename)) self.img_grey = cv2.cvtColor(self.img_orig, cv2.COLOR_BGR2GRAY) _, self.img_contour = cv2.threshold(self.img_grey, 250, 255, cv2.THRESH_BINARY_INV) _, self.img_text = cv2.threshold(self.img_grey, 150, 255, cv2.THRESH_BINARY) self.root_node = None self.contours = self.find_contours() self.contour_lines, self.contour_nodes = self.categorize_contours() self.build_graph() self.build_parse_tree() self.parse_nodes() if not analyze_only: self.python_ast = self.root_node.to_python_ast()
def get_data(self): idxs = np.arange(len(self.train_list)) if self.shuffle: self.rng.shuffle(idxs) caches = {} for i, k in enumerate(idxs): path = self.train_list[k] label = self.lb_list[k] if i % self.preload == 0: try: caches = ILSVRCTenth._read_tenth_batch(self.train_list[idxs[i:i+self.preload]]) except Exception as e: logging.warning('tenth local cache failed, err=%s' % str(e)) content = caches.get(path, '') if not content: content = ILSVRCTenth._read_tenth(path) img = cv2.imdecode(np.fromstring(content, dtype=np.uint8), cv2.IMREAD_COLOR) yield [img, label]
def build(dirPath,filename = None): if filename is None: spook = Illumify(getVapor()) filename = spook.getFilename() spooky_x, spooky_y = spook.generate() else: spook = Illumify(filename) filename = spook.getFilename() spooky_x, spooky_y = spook.generate() dst = copy = img = cv2.imread(filename, cv2.IMREAD_COLOR) orig_h, orig_w = img.shape[:2] #cv2.imwrite("image005."+filename.split(".")[1],dst) h_o,w_o = copy.shape[:2] step_h = h_o/5 step_w = w_o/5 for i in range(1,5): h = h_o - step_h*i w = w_o - step_w*i crop_image = img[spooky_x:spooky_x+h, spooky_y:spooky_y+h] dst = cv2.resize(crop_image,(orig_w,orig_h)) cv2.imwrite(dirPath+"/image00" + str(i) +"."+get_filetype(filename),dst)
def upload(): # Get the name of the uploaded file file = request.files['file'] # Check if the file is one of the allowed types/extensions if file and allowed_file(file.filename): # Make the filename safe, remove unsupported chars filename = secure_filename(file.filename) # Move the file form the temporal folder to # the upload folder we setup file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) # Redirect the user to the uploaded_file route, which # will basicaly show on the browser the uploaded file # CV2 #img_np = cv2.imdecode(np.fromstring(file.read(), np.uint8), cv2.IMREAD_UNCHANGED) # cv2.IMREAD_COLOR in OpenCV 3.1 img_np = cv2.imread(os.path.join(app.config['UPLOAD_FOLDER'], filename), -1) cv2.imshow("Image", img_np) return redirect(url_for('uploaded_file', filename=filename)) # This route is expecting a parameter containing the name # of a file. Then it will locate that file on the upload # directory and show it on the browser, so if the user uploads # an image, that image is going to be show after the upload
def pull_image(self, index): '''Returns the original image object at index in PIL form Note: not using self.__getitem__(), as any transformations passed in could mess up this functionality. Argument: index (int): index of img to show Return: PIL img ''' img_id = self.ids[index] img = cv2.imread(self._imgpath % img_id, cv2.IMREAD_COLOR) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) return img # return imread(self._imgpath % img_id)
def __getitem__(self, index): datafiles = self.files[index] image = cv2.imread(datafiles["img"], cv2.IMREAD_COLOR) size = image.shape name = osp.splitext(osp.basename(datafiles["img"]))[0] image = np.asarray(image, np.float32) image -= self.mean img_h, img_w, _ = image.shape pad_h = max(self.crop_h - img_h, 0) pad_w = max(self.crop_w - img_w, 0) if pad_h > 0 or pad_w > 0: image = cv2.copyMakeBorder(image, 0, pad_h, 0, pad_w, cv2.BORDER_CONSTANT, value=(0.0, 0.0, 0.0)) image = image.transpose((2, 0, 1)) return image, name, size
def hookTrainData(self, sampleIdxs): assert len(sampleIdxs) > 0, 'we need a non-empty batch list' source_list, target_list, label_list = [], [], [] for idx in sampleIdxs: classList = self.trainDict[idx] img_pair = classList[np.random.choice(self.trainLenClass[idx], 1)] prev_img = img_pair[0] next_img = img_pair[1] label = idx # print prev_img, next_img, label source = cv2.imread(os.path.join(self.img_path, prev_img), cv2.IMREAD_COLOR) target = cv2.imread(os.path.join(self.img_path, next_img), cv2.IMREAD_COLOR) source_list.append(np.expand_dims(cv2.resize(source, (self.image_size[1], self.image_size[0])), 0)) target_list.append(np.expand_dims(cv2.resize(target, (self.image_size[1], self.image_size[0])) ,0)) label_list.append(np.expand_dims(label, 0)) return np.concatenate(source_list, axis=0), np.concatenate(target_list, axis=0), np.concatenate(label_list, axis=0) # Adding the channel dimension if images are read in grayscale # return np.expand_dims(source_list, axis = 3), np.expand_dims(target_list, axis = 3)
def hookTrainData(self, sampleIdxs): assert len(sampleIdxs) > 0, 'we need a non-empty batch list' input_list, flow_list = [], [] for idx in sampleIdxs: img_list = self.trainList[idx] multi_input = [] multi_flow = [] for time_idx in xrange(self.time_step): imgData = cv2.imread(os.path.join(self.img_path, img_list[time_idx]), cv2.IMREAD_COLOR) multi_input.append(np.expand_dims(cv2.resize(imgData, (self.image_size[1], self.image_size[0])), 0)) # We have self.time_step images, but self.time_step - 1 flows. if time_idx != self.time_step - 1: flow = utils.readFlow(os.path.join(self.data_path, 'training', "flow", (img_list[time_idx][:-4] + ".flo"))) multi_flow.append(np.expand_dims(flow, 0)) input_list.append(np.concatenate(multi_input, axis=3)) flow_list.append(np.concatenate(multi_flow, axis=3)) return np.concatenate(input_list, axis=0), np.concatenate(flow_list, axis=0)
def hookValData(self, sampleIdxs): assert len(sampleIdxs) > 0, 'we need a non-empty batch list' input_list, flow_list = [], [] for idx in sampleIdxs: img_list = self.valList[idx] multi_input = [] multi_flow = [] for time_idx in xrange(self.time_step): imgData = cv2.imread(os.path.join(self.img_path, img_list[time_idx]), cv2.IMREAD_COLOR) multi_input.append(np.expand_dims(cv2.resize(imgData, (self.image_size[1], self.image_size[0])), 0)) # We have self.time_step images, but self.time_step - 1 flows. if time_idx != self.time_step - 1: flow = utils.readFlow(os.path.join(self.data_path, 'training', "flow", (img_list[time_idx][:-4] + ".flo"))) multi_flow.append(np.expand_dims(flow, 0)) input_list.append(np.concatenate(multi_input, axis=3)) flow_list.append(np.concatenate(multi_flow, axis=3)) return np.concatenate(input_list, axis=0), np.concatenate(flow_list, axis=0)
def calculateMean(self): numSamples = len(self.trainList) # OpenCV loads image as BGR order B, G, R = 0, 0, 0 for idx in xrange(numSamples): frameID = self.trainList[idx] prev_img = frameID[0] next_img = frameID[1] source = cv2.imread(os.path.join(self.img_path, prev_img), cv2.IMREAD_COLOR) target = cv2.imread(os.path.join(self.img_path, next_img), cv2.IMREAD_COLOR) B += np.mean(source[:,:,0], axis=None) B += np.mean(target[:,:,0], axis=None) G += np.mean(source[:,:,1], axis=None) G += np.mean(target[:,:,1], axis=None) R += np.mean(source[:,:,2], axis=None) R += np.mean(target[:,:,2], axis=None) B = B / (2*numSamples) G = G / (2*numSamples) R = R / (2*numSamples) return (B,G,R)
def calculateMean(self): numSamples = len(self.trainList) # OpenCV loads image as BGR order B, G, R = 0, 0, 0 for idx in xrange(numSamples): frameID = self.trainList[idx] prev_img = frameID + "_img1.ppm" next_img = frameID + "_img2.ppm" source = cv2.imread(os.path.join(self.img_path, prev_img), cv2.IMREAD_COLOR) target = cv2.imread(os.path.join(self.img_path, next_img), cv2.IMREAD_COLOR) B += np.mean(source[:,:,0], axis=None) B += np.mean(target[:,:,0], axis=None) G += np.mean(source[:,:,1], axis=None) G += np.mean(target[:,:,1], axis=None) R += np.mean(source[:,:,2], axis=None) R += np.mean(target[:,:,2], axis=None) B = B / (2*numSamples) G = G / (2*numSamples) R = R / (2*numSamples) return (B,G,R)
def hookTrainData(self, sampleIdxs): assert len(sampleIdxs) > 0, 'we need a non-empty batch list' source_list, target_list, label_list = [], [], [] for idx in sampleIdxs: classList = self.trainDict[idx] img_pair = classList[np.random.choice(self.trainLenClass[idx], 1)] prev_img = img_pair[0] next_img = img_pair[1] label = idx # print prev_img, next_img, label source = cv2.imread(os.path.join(self.img_path, prev_img), cv2.IMREAD_COLOR) target = cv2.imread(os.path.join(self.img_path, next_img), cv2.IMREAD_COLOR) if self.is_crop: source = cv2.resize(source, (self.crop_size[1], self.crop_size[0])) target = cv2.resize(target, (self.crop_size[1], self.crop_size[0])) source_list.append(np.expand_dims(source, 0)) target_list.append(np.expand_dims(target, 0)) label_list.append(np.expand_dims(label, 0)) return np.concatenate(source_list, axis=0), np.concatenate(target_list, axis=0), np.concatenate(label_list, axis=0)
def hookValData(self, sampleIdxs, classID): assert len(sampleIdxs) > 0, 'we need a non-empty batch list' source_list, target_list, label_list = [], [], [] for idx in sampleIdxs: img_pair = self.testDict[classID][idx] prev_img = img_pair[0] next_img = img_pair[1] source = cv2.imread(os.path.join(self.img_path, prev_img), cv2.IMREAD_COLOR) target = cv2.imread(os.path.join(self.img_path, next_img), cv2.IMREAD_COLOR) if self.is_crop: source = cv2.resize(source, (self.crop_size[1], self.crop_size[0])) target = cv2.resize(target, (self.crop_size[1], self.crop_size[0])) source_list.append(np.expand_dims(source, 0)) target_list.append(np.expand_dims(target, 0)) label_list.append(np.expand_dims(classID, 0)) # print prev_img, next_img, classID return np.concatenate(source_list, axis=0), np.concatenate(target_list, axis=0), np.concatenate(label_list, axis=0)
def hookTrainData(self, sampleIdxs): assert len(sampleIdxs) > 0, 'we need a non-empty batch list' source_list, target_list, flow_gt = [], [], [] for idx in sampleIdxs: img_pair = self.trainList[idx] prev_img = img_pair[0] next_img = img_pair[1] source = cv2.imread(os.path.join(self.img_path, prev_img), cv2.IMREAD_COLOR) target = cv2.imread(os.path.join(self.img_path, next_img), cv2.IMREAD_COLOR) flow = utils.readFlow(os.path.join(self.data_path, 'training', "flow", (prev_img[:-4] + ".flo"))) if self.is_crop: source = cv2.resize(source, (self.crop_size[1], self.crop_size[0])) target = cv2.resize(target, (self.crop_size[1], self.crop_size[0])) source_list.append(np.expand_dims(source, 0)) target_list.append(np.expand_dims(target, 0)) flow_gt.append(np.expand_dims(flow, 0)) return np.concatenate(source_list, axis=0), np.concatenate(target_list, axis=0), np.concatenate(flow_gt, axis=0)
def hookTrainData(self, sampleIdxs): assert len(sampleIdxs) > 0, 'we need a non-empty batch list' source_list, target_list, flow_gt = [], [], [] for idx in sampleIdxs: frameID = self.trainList[idx] prev_img = frameID + "_img1.ppm" next_img = frameID + "_img2.ppm" source = cv2.imread(os.path.join(self.img_path, prev_img), cv2.IMREAD_COLOR) target = cv2.imread(os.path.join(self.img_path, next_img), cv2.IMREAD_COLOR) # print source.shape flow = utils.readFlow(os.path.join(self.img_path, (frameID + "_flow.flo"))) # print flow.shape if self.is_crop: source = cv2.resize(source, (self.crop_size[1], self.crop_size[0])) target = cv2.resize(target, (self.crop_size[1], self.crop_size[0])) source_list.append(np.expand_dims(source, 0)) target_list.append(np.expand_dims(target ,0)) flow_gt.append(np.expand_dims(flow, 0)) return np.concatenate(source_list, axis=0), np.concatenate(target_list, axis=0), np.concatenate(flow_gt, axis=0)
def hookValData(self, sampleIdxs): assert len(sampleIdxs) > 0, 'we need a non-empty batch list' source_list, target_list, flow_gt = [], [], [] for idx in sampleIdxs: frameID = self.valList[idx] prev_img = frameID + "_img1.ppm" next_img = frameID + "_img2.ppm" source = cv2.imread(os.path.join(self.img_path, prev_img), cv2.IMREAD_COLOR) target = cv2.imread(os.path.join(self.img_path, next_img), cv2.IMREAD_COLOR) flow = utils.readFlow(os.path.join(self.img_path, (frameID + "_flow.flo"))) if self.is_crop: source = cv2.resize(source, (self.crop_size[1], self.crop_size[0])) target = cv2.resize(target, (self.crop_size[1], self.crop_size[0])) source_list.append(np.expand_dims(source, 0)) target_list.append(np.expand_dims(target ,0)) flow_gt.append(np.expand_dims(flow, 0)) return np.concatenate(source_list, axis=0), np.concatenate(target_list, axis=0), np.concatenate(flow_gt, axis=0)
def calculateMean(self): numSamples = self.trainNum # OpenCV loads image as BGR order B, G, R = 0, 0, 0 for idx in xrange(numSamples): frameID = self.trainList[idx] prev_img = frameID + "_img1.ppm" next_img = frameID + "_img2.ppm" source = cv2.imread(os.path.join(self.img_path, prev_img), cv2.IMREAD_COLOR) target = cv2.imread(os.path.join(self.img_path, next_img), cv2.IMREAD_COLOR) B += np.mean(source[:,:,0], axis=None) B += np.mean(target[:,:,0], axis=None) G += np.mean(source[:,:,1], axis=None) G += np.mean(target[:,:,1], axis=None) R += np.mean(source[:,:,2], axis=None) R += np.mean(target[:,:,2], axis=None) B = B / (2*numSamples) G = G / (2*numSamples) R = R / (2*numSamples) return (B,G,R)
def __iter__(self): for k in range(self.count / self.batch_size): data = [] label = [] for i in range(self.batch_size): num = gen_rand() img = self.captcha.generate(num) img = np.fromstring(img.getvalue(), dtype='uint8') img = cv2.imdecode(img, cv2.IMREAD_COLOR) img = cv2.resize(img, (self.width, self.height)) cv2.imwrite("./tmp" + str(i % 10) + ".png", img) img = np.multiply(img, 1/255.0) img = img.transpose(2, 0, 1) data.append(img) label.append(get_label(num)) data_all = [mx.nd.array(data)] label_all = [mx.nd.array(label)] data_names = ['data'] label_names = ['softmax_label'] data_batch = OCRBatch(data_names, data_all, label_names, label_all) yield data_batch
def __init__(self, content=None, image=None): self.image = None self.format = None if isinstance(image, Image): self.image = image.image self.format = image.format elif image is not None: self.image = image elif content: image_format = imghdr.what(file='', h=content) if image_format is not None: image_array = np.fromstring(content, np.uint8) self.image = cv2.imdecode(image_array, cv2.IMREAD_COLOR) self.format = image_format if self.image is None: raise click.BadParameter('Image format not supported')
def _grab_image(path=None, stream=None, url=None): # if the path is not None, then load the image from disk if path is not None: image = cv2.imread(path) # otherwise, the image does not reside on disk else: # if the URL is not None, then download the image if url is not None: resp = urllib.urlopen(url) data = resp.read() # if the stream is not None, then the image has been uploaded elif stream is not None: data = stream.read() # convert the image to a NumPy array and then read it into # OpenCV format image = np.asarray(bytearray(data), dtype="uint8") image = cv2.imdecode(image, cv2.IMREAD_COLOR) # return the image return image
def get_mean_image_path(self): if not os.path.exists(self.outputfolder+'/'+self.mean_image_filename): print('no mean image found. Creating...') isomap_size = cv2.imread(self.examples_train[0].images[0], cv2.IMREAD_COLOR).shape[0] mean = np.zeros([isomap_size, isomap_size, 3], dtype='float32') for example in self.examples_train:# try: mean+=cv2.imread(example.images[0],cv2.IMREAD_COLOR).astype(dtype='float32')/len(self.examples_train) except: e = sys.exc_info()[0] print (str(e)) print ('image', example.images[0]) exit(0) #mean/=len(self.images_train) mean_uint8 = mean.astype(dtype='uint8') cv2.imwrite(self.outputfolder+'/'+self.mean_image_filename, mean_uint8) return self.outputfolder+'/'+self.mean_image_filename
def augmentImages(train_or_valid, image_dir, img_save_dir, save_file): if train_or_valid == "train": # Training print("Augment Training Data") else: # Validation print("Augment Validation Data") image_set = glob.glob(image_dir + "*.jpg") aug_no = 16 image_len = len(image_set) for index, img in enumerate(image_set): img_name = img.split("/")[-1] x = cv2.imread(img, cv2.IMREAD_COLOR) # print x.shape print("Augmenting Image : {0} / {1} - {2}".format(index, image_len, img_name)) augment(x, aug_no, img_save_dir, img_name)
def start_stream(self): bytes = None print("starting stream...") stream = urllib2.urlopen(self.address) #'http://192.168.100.102:8080/video' bytes = b'' while True: bytes += stream.read(1024) a = bytes.find(b'\xff\xd8') b = bytes.find(b'\xff\xd9') if a != -1 and b != -1: jpg = bytes[a:b+2] bytes = bytes[b+2:] self.image = cv2.cvtColor(cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.IMREAD_COLOR), cv2.COLOR_BGR2RGB) #cv2.imshow('i', self.image) #cv2.waitKey(1)
def test_detector(): print('test detector:') # load model detector = Detector('SeetaFaceEngine/model/seeta_fd_frontal_v1.0.bin') detector.set_min_face_size(30) image_color = cv2.imread('data/chloecalmon.png', cv2.IMREAD_COLOR) image_gray = cv2.cvtColor(image_color, cv2.COLOR_BGR2GRAY) faces = detector.detect(image_gray) for i, face in enumerate(faces): print('({0},{1},{2},{3}) score={4}'.format(face.left, face.top, face.right, face.bottom, face.score)) cv2.rectangle(image_color, (face.left, face.top), (face.right, face.bottom), (0,255,0), thickness=2) cv2.putText(image_color, str(i), (face.left, face.bottom),cv2.FONT_HERSHEY_COMPLEX, 1, (0,255,0), thickness=1) cv2.imshow('test', image_color) cv2.waitKey(0) detector.release()
def test_aligner(): print('test aligner:') # load model detector = Detector('SeetaFaceEngine/model/seeta_fd_frontal_v1.0.bin') detector.set_min_face_size(30) aligner = Aligner('SeetaFaceEngine/model/seeta_fa_v1.1.bin') image_color = cv2.imread('data/chloecalmon.png', cv2.IMREAD_COLOR) image_gray = cv2.cvtColor(image_color, cv2.COLOR_BGR2GRAY) faces = detector.detect(image_gray) for face in faces: landmarks = aligner.align(image_gray, face) for point in landmarks: cv2.circle(image_color, point, 1, (0,255,0), 2) cv2.imshow('test aligner', image_color) cv2.waitKey(0) aligner.release() detector.release()
def load(self): if self.imageType == InputType.image: self.data = cv2.cvtColor(cv2.imread(self.filePath, cv2.IMREAD_COLOR), cv2.COLOR_BGR2RGB) self.state = LoadState.loaded if self.imageType == InputType.imageGrayscale: self.data = cv2.cvtColor(cv2.imread(self.filePath, cv2.IMREAD_COLOR), cv2.COLOR_BGR2GRAY) self.state = LoadState.loaded elif self.imageType == InputType.saliencyMapMatlab: self.data = (scipy.io.loadmat(self.filePath)['I'] * 255).astype(np.uint8) self.state = LoadState.loaded elif self.imageType == InputType.fixationMapMatlab: self.data = (scipy.io.loadmat(self.filePath)['I']).nonzero() self.state = LoadState.loaded elif self.imageType == InputType.empty: self.data = None
def nextBatch(self, batches, dataset='train'): imgH = 300 imgW = 300 if dataset == 'train': datalist = self.trainList if dataset == 'test': datalist = self.testList randomIndex = random.sample(range(len(datalist)), batches) images = [] for index in randomIndex: fileName = './svt1/' + datalist[index][0] img = cv2.imread(fileName, cv2.IMREAD_COLOR) resized = cv2.resize(img, (imgW, imgH)) resized = np.multiply(resized, 1.0/255.0) images.append(resized) anns.append(datalist[x][1]) images = np.asarray(images) return (images, anns)
def browse(database): for item in database: filename = os.path.split(item['url'])[-1] path = image_root + filename img = cv2.imread(path, cv2.IMREAD_COLOR) crop = item['crop'] x = crop[0] y = crop[1] w = crop[2] h = crop[3] # Error handling if img is None: puts(colored.red('ERROR: loading image failed!')) continue cv2.rectangle(img, (x,y), (x+w, y+h), (0,255,0), 2) cv2.imshow('Cropping', img) key = cv2.waitKey() if key == 1048603: print 'exit' break
def load_lmdb(lmdb_file, n_records=None): import lmdb import numpy as np lmdb_file = expand_user(lmdb_file) if os.path.exists(lmdb_file): data = [] env = lmdb.open(lmdb_file, readonly=True, max_readers=512) with env.begin() as txn: cursor = txn.cursor() begin_st = time.time() print("Loading lmdb file {} into memory".format(lmdb_file)) for key, value in cursor: _, target, _ = key.decode('ascii').split(':') target = int(target) img = cv2.imdecode(np.fromstring(value, np.uint8), cv2.IMREAD_COLOR) data.append((img, target)) if n_records is not None and len(data) >= n_records: break env.close() print("=> Done ({:.4f} s)".format(time.time() - begin_st)) return data else: print("Not found lmdb file".format(lmdb_file))
def exportSurfaceMask(overwriteSource): terrainSplatMaskPath = bpy.data.scenes["Default_Location"].ImportTerrainSplatMaskPath if bpy.context.scene.SurfaceMaskFormatValid: print('\nbLT_Info: Surface map export started ', time.ctime()) from cv2 import imread as cv2imread, imwrite as cv2imwrite, IMREAD_COLOR as cv2IMREAD_COLOR ProjFolderPath = bpy.data.scenes["Default_Location"].ProjFolderPath locationName = bpy.context.scene.name sourceSurfaceMask = cv2imread(bpy.data.scenes["Default_Location"].ImportTerrainSplatMaskPath, cv2IMREAD_COLOR) locationSurfaceMask = cv2imread(r'{}ProjectData\Textures\TerrainMask_{}.png'.format(ProjFolderPath,locationName), cv2IMREAD_COLOR) terrainObject = bpy.data.objects.get('Terrain_{}'.format(locationName)) sourceSurfaceMask[terrainObject['MergeTopLeftY']:terrainObject["MergeBottomRightY"],terrainObject["MergeTopLeftX"]:terrainObject["MergeBottomRightX"]] = locationSurfaceMask if overwriteSource: outputPath = terrainSplatMaskPath else: outputPath = '{}\\Output\\surfaceMask.png'.format(ProjFolderPath) cv2imwrite(outputPath, sourceSurfaceMask) print('bLT_Info: Surface map export finished ', time.ctime()) else: print('\nbLT_Info:No surface map data exported!!! Source surface mask path not defined in Data Sources panel.')
def process_image(img, img_size, pixel_depth): ''' Maintain aspect ratio of image while resizing ''' img = cv2.imread(img, cv2.IMREAD_COLOR) if (img.shape[0] >= img.shape[1]): # height is greater than width resizeto = (img_size, int( round(img_size * (float(img.shape[1]) / img.shape[0])))) else: resizeto = ( int(round(img_size * (float(img.shape[0]) / img.shape[1]))), img_size) img = cv2.resize(img, (resizeto[1], resizeto[ 0]), interpolation=cv2.INTER_CUBIC) img = cv2.copyMakeBorder( img, 0, img_size - img.shape[0], 0, img_size - img.shape[1], cv2.BORDER_CONSTANT, 0) img = normalize_image(img, pixel_depth) return img[:, :, ::-1] # turn into rgb format
def test_solution_close_to_original_implementation(self): image = cv2.imread('testdata/source.png', cv2.IMREAD_COLOR) / 255.0 scribles = cv2.imread('testdata/scribbles.png', cv2.IMREAD_COLOR) / 255.0 alpha = closed_form_matting.closed_form_matting_with_scribbles(image, scribles) foreground, background = solve_foreground_background(image, alpha) matlab_alpha = cv2.imread('testdata/matlab_alpha.png', cv2.IMREAD_GRAYSCALE) / 255.0 matlab_foreground = cv2.imread('testdata/matlab_foreground.png', cv2.IMREAD_COLOR) / 255.0 matlab_background = cv2.imread('testdata/matlab_background.png', cv2.IMREAD_COLOR) / 255.0 sad_alpha = np.mean(np.abs(alpha - matlab_alpha)) sad_foreground = np.mean(np.abs(foreground - matlab_foreground)) sad_background = np.mean(np.abs(background - matlab_background)) self.assertLess(sad_alpha, 1e-2) self.assertLess(sad_foreground, 1e-2) self.assertLess(sad_background, 1e-2)
def decode(self, byte_list): return cv2.imdecode(byte_list, cv2.IMREAD_COLOR)
def image_loop(): image_counter = 0 while True: # path = '/Users/vmagro/Developer/frc/RealFullField/11.jpg' # path = '/Users/vmagro/Developer/frc/Vision2016/test/img/11.jpg' path = '/Users/vmagro/Developer/frc/RealFullField/' + str(image_counter) + '.jpg' img = cv2.imread(path, cv2.IMREAD_COLOR) image_counter = (image_counter + 1) % 350 handle_image(img) time.sleep(33 / 1000) # slow down so its visible
def read_im(self,fname,scale=1): ''' ???? ''' # ============================================================================= # im = cv2.imread(fname, cv2.IMREAD_COLOR) # ============================================================================= im = cv2.imdecode(np.fromfile(fname,dtype=np.uint8),-1) if type(im)==type(None): print(fname) raise ValueError('Opencv read image {} error, got None'.format(fname)) return im
def pull_image(self, index): '''Returns the original image object at index in PIL form Note: not using self.__getitem__(), as any transformations passed in could mess up this functionality. Argument: index (int): index of img to show Return: PIL img ''' img_id = self.ids[index] return cv2.imread(self._imgpath % img_id, cv2.IMREAD_COLOR)
def image_from_archive(archive, name): """ Load image PGM file from tar archive. Used for tarfile loading and unit test. """ member = archive.getmember(name) imagefiledata = numpy.fromstring(archive.extractfile(member).read(-1), numpy.uint8) imagefiledata.resize((1, imagefiledata.size)) return cv2.imdecode(imagefiledata, cv2.IMREAD_COLOR)
def url_to_image(url): # download the image, convert it to a NumPy array, and then read # it into OpenCV format resp = urllib.urlopen(url) image = np.asarray(bytearray(resp.read()), dtype="uint8") image = cv2.imdecode(image, cv2.IMREAD_COLOR) # return the image return image
def read_image(file_path): img = cv2.imread(file_path, cv2.IMREAD_COLOR) # cv2.IMREAD_GRAYSCALE if (img.shape[0] >= img.shape[1]): # height is greater than width resizeto = (IMAGE_SIZE, int(round(IMAGE_SIZE * (float(img.shape[1]) / img.shape[0])))); else: resizeto = (int(round(IMAGE_SIZE * (float(img.shape[0]) / img.shape[1]))), IMAGE_SIZE); img2 = cv2.resize(img, (resizeto[1], resizeto[0]), interpolation=cv2.INTER_CUBIC) img3 = cv2.copyMakeBorder(img2, 0, IMAGE_SIZE - img2.shape[0], 0, IMAGE_SIZE - img2.shape[1], cv2.BORDER_CONSTANT, 0) return img3[:, :, ::-1] # turn into rgb format
def read_im_and_landmarks(fname): im = cv2.imread(fname, cv2.IMREAD_COLOR) try: s = get_landmarks(im,fname) return im, s except: return im,fname
def load_image(self, img_id): img = self.coco.loadImgs(img_id)[0] img_str = '%simages/%s/%s' % (self.root, self.real_split, img['file_name']) if self.split == 'test-dev2015': img_str = img_str.replace('test-dev2015', 'test2015') im = cv2.imread(img_str, cv2.IMREAD_COLOR) im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)/255.0 im = im.astype(np.float32) return im