Python cv2.CV_LOAD_IMAGE_COLOR Examples

The following are 15 code examples of cv2.CV_LOAD_IMAGE_COLOR(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cv2 , or try the search function .
Example #1
Source File: gen_megaface.py    From insightface with MIT License 5 votes vote down vote up
def read_img(image_path):
  img = cv2.imread(image_path, cv2.CV_LOAD_IMAGE_COLOR)
  return img 
Example #2
Source File: face_preprocess.py    From insightface with MIT License 5 votes vote down vote up
def read_image(img_path, **kwargs):
  mode = kwargs.get('mode', 'rgb')
  layout = kwargs.get('layout', 'HWC')
  if mode=='gray':
    img = cv2.imread(img_path, cv2.CV_LOAD_IMAGE_GRAYSCALE)
  else:
    img = cv2.imread(img_path, cv2.CV_LOAD_IMAGE_COLOR)
    if mode=='rgb':
      #print('to rgb')
      img = img[...,::-1]
    if layout=='CHW':
      img = np.transpose(img, (2,0,1))
  return img 
Example #3
Source File: recognizer.py    From njucaptcha with GNU General Public License v2.0 5 votes vote down vote up
def get_captcha(captcha_str):
    nparr = np.fromstring(captcha_str, np.uint8)
    ptcha = cv2.imdecode(nparr, cv2.CV_LOAD_IMAGE_COLOR)
    captcha.shape = -1,
    captcha = (captcha[::3].astype(np.int) + captcha[1::3].astype(np.int) + captcha[2::3].astype(np.int)) / 3
    captcha = (255 - captcha).astype(np.uint8)
    return captcha 
Example #4
Source File: word_container.py    From phocnet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_word_image(self, gray_scale=True):
        col_type = None
        if gray_scale:
            col_type = cv2.CV_LOAD_IMAGE_GRAYSCALE
        else:
            col_type = cv2.CV_LOAD_IMAGE_COLOR
        
        # load the image
        ul = self.bounding_box['upperLeft']
        wh = self.bounding_box['widthHeight']
        img = cv2.imread(self.image_path, col_type)
        if not np.all(self.bounding_box['widthHeight'] == -1):
            img = img[ul[1]:ul[1]+wh[1], ul[0]:ul[0]+wh[0]]
        return img 
Example #5
Source File: gen_megaface.py    From 1.FaceRecognition with MIT License 5 votes vote down vote up
def read_img(image_path):
  img = cv2.imread(image_path, cv2.CV_LOAD_IMAGE_COLOR)
  return img 
Example #6
Source File: face_preprocess.py    From 1.FaceRecognition with MIT License 5 votes vote down vote up
def read_image(img_path, **kwargs):
  mode = kwargs.get('mode', 'rgb')
  layout = kwargs.get('layout', 'HWC')
  if mode=='gray':
    img = cv2.imread(img_path, cv2.CV_LOAD_IMAGE_GRAYSCALE)
  else:
    img = cv2.imread(img_path, cv2.CV_LOAD_IMAGE_COLOR)
    if mode=='rgb':
      #print('to rgb')
      img = img[...,::-1]
    if layout=='CHW':
      img = np.transpose(img, (2,0,1))
  return img 
Example #7
Source File: __init__.py    From pyscreeze with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _load_cv2(img, grayscale=None):
    """
    TODO
    """
    # load images if given filename, or convert as needed to opencv
    # Alpha layer just causes failures at this point, so flatten to RGB.
    # RGBA: load with -1 * cv2.CV_LOAD_IMAGE_COLOR to preserve alpha
    # to matchTemplate, need template and image to be the same wrt having alpha

    if grayscale is None:
        grayscale = GRAYSCALE_DEFAULT
    if isinstance(img, (str, unicode)):
        # The function imread loads an image from the specified file and
        # returns it. If the image cannot be read (because of missing
        # file, improper permissions, unsupported or invalid format),
        # the function returns an empty matrix
        # http://docs.opencv.org/3.0-beta/modules/imgcodecs/doc/reading_and_writing_images.html
        if grayscale:
            img_cv = cv2.imread(img, LOAD_GRAYSCALE)
        else:
            img_cv = cv2.imread(img, LOAD_COLOR)
        if img_cv is None:
            raise IOError("Failed to read %s because file is missing, "
                          "has improper permissions, or is an "
                          "unsupported or invalid format" % img)
    elif isinstance(img, numpy.ndarray):
        # don't try to convert an already-gray image to gray
        if grayscale and len(img.shape) == 3:  # and img.shape[2] == 3:
            img_cv = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        else:
            img_cv = img
    elif hasattr(img, 'convert'):
        # assume its a PIL.Image, convert to cv format
        img_array = numpy.array(img.convert('RGB'))
        img_cv = img_array[:, :, ::-1].copy()  # -1 does RGB -> BGR
        if grayscale:
            img_cv = cv2.cvtColor(img_cv, cv2.COLOR_BGR2GRAY)
    else:
        raise TypeError('expected an image filename, OpenCV numpy array, or PIL image')
    return img_cv 
Example #8
Source File: face_preprocess.py    From bootcamp with Apache License 2.0 5 votes vote down vote up
def read_image(img_path, **kwargs):
  mode = kwargs.get('mode', 'rgb')
  layout = kwargs.get('layout', 'HWC')
  if mode=='gray':
    img = cv2.imread(img_path, cv2.CV_LOAD_IMAGE_GRAYSCALE)
  else:
    img = cv2.imread(img_path, cv2.CV_LOAD_IMAGE_COLOR)
    if mode=='rgb':
      #print('to rgb')
      img = img[...,::-1]
    if layout=='CHW':
      img = np.transpose(img, (2,0,1))
  return img 
Example #9
Source File: __init__.py    From Dindo-Bot with MIT License 5 votes vote down vote up
def _load_cv2(img, grayscale=None):
    """
    TODO
    """
    # load images if given filename, or convert as needed to opencv
    # Alpha layer just causes failures at this point, so flatten to RGB.
    # RGBA: load with -1 * cv2.CV_LOAD_IMAGE_COLOR to preserve alpha
    # to matchTemplate, need template and image to be the same wrt having alpha

    if grayscale is None:
        grayscale = GRAYSCALE_DEFAULT
    if isinstance(img, (str, unicode)):
        # The function imread loads an image from the specified file and
        # returns it. If the image cannot be read (because of missing
        # file, improper permissions, unsupported or invalid format),
        # the function returns an empty matrix
        # http://docs.opencv.org/3.0-beta/modules/imgcodecs/doc/reading_and_writing_images.html
        if grayscale:
            img_cv = cv2.imread(img, LOAD_GRAYSCALE)
        else:
            img_cv = cv2.imread(img, LOAD_COLOR)
        if img_cv is None:
            raise IOError("Failed to read %s because file is missing, "
                          "has improper permissions, or is an "
                          "unsupported or invalid format" % img)
    elif isinstance(img, numpy.ndarray):
        # don't try to convert an already-gray image to gray
        if grayscale and len(img.shape) == 3:  # and img.shape[2] == 3:
            img_cv = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        else:
            img_cv = img
    elif hasattr(img, 'convert'):
        # assume its a PIL.Image, convert to cv format
        img_array = numpy.array(img.convert('RGB'))
        img_cv = img_array[:, :, ::-1].copy()  # -1 does RGB -> BGR
        if grayscale:
            img_cv = cv2.cvtColor(img_cv, cv2.COLOR_BGR2GRAY)
    else:
        raise TypeError('expected an image filename, OpenCV numpy array, or PIL image')
    return img_cv 
Example #10
Source File: classifiers.py    From DeepClassificationBot with MIT License 5 votes vote down vote up
def fetch_cvimage_from_url(url, maxsize=10 * 1024 * 1024):
    req = requests.get(url, timeout=5, stream=True)
    content = ''
    for chunk in req.iter_content(2048):
        content += chunk
        if len(content) > maxsize:
            req.close()
            raise ValueError('Response too large')
    img_array = np.asarray(bytearray(content), dtype=np.uint8)
    cv2_img_flag = cv2.CV_LOAD_IMAGE_COLOR
    image = cv2.imdecode(img_array, cv2_img_flag)
    return image 
Example #11
Source File: face_preprocess.py    From MaskInsightface with Apache License 2.0 5 votes vote down vote up
def read_image(img_path, **kwargs):
  mode = kwargs.get('mode', 'rgb')
  layout = kwargs.get('layout', 'HWC')
  if mode=='gray':
    img = cv2.imread(img_path, cv2.CV_LOAD_IMAGE_GRAYSCALE)
  else:
    img = cv2.imread(img_path, cv2.CV_LOAD_IMAGE_COLOR)
    if mode=='rgb':
      #print('to rgb')
      img = img[...,::-1]
    if layout=='CHW':
      img = np.transpose(img, (2,0,1))
  return img 
Example #12
Source File: face_preprocess.py    From MaskInsightface with Apache License 2.0 5 votes vote down vote up
def read_image(img_path, **kwargs):
  mode = kwargs.get('mode', 'rgb')
  layout = kwargs.get('layout', 'HWC')
  if mode=='gray':
    img = cv2.imread(img_path, cv2.CV_LOAD_IMAGE_GRAYSCALE)
  else:
    img = cv2.imread(img_path, cv2.CV_LOAD_IMAGE_COLOR)
    if mode=='rgb':
      #print('to rgb')
      img = img[...,::-1]
    if layout=='CHW':
      img = np.transpose(img, (2,0,1))
  return img 
Example #13
Source File: video_io.py    From DetectAndTrack with Apache License 2.0 5 votes vote down vote up
def H5ToVideo(fpath, frames_to_read=None):
    """Read frames from the h5 file.
    Args:
        fpath (str): Filename of h5 file
        frames_to_read (list or None): List of frames to read. None => all frames
    """
    res = []
    with h5py.File(fpath, 'r') as fin:
        nframes = len(fin['frames'])
        if frames_to_read is None:
            frames_to_read = range(nframes)
        grp = fin['frames']
        for fid in frames_to_read:
            res.append(cv2.imdecode(grp[str(fid)].value, cv2.CV_LOAD_IMAGE_COLOR))
    return np.transpose(np.stack(res), (0, 3, 1, 2)) 
Example #14
Source File: video_io.py    From DetectAndTrack with Apache License 2.0 5 votes vote down vote up
def StringArrayElementToFrame(string_array, i):
    return cv2.imdecode(np.fromstring(
        string_array[i].tostring(), np.uint8), cv2.CV_LOAD_IMAGE_COLOR) 
Example #15
Source File: load_img.py    From Dense-CoAttention-Network with MIT License 4 votes vote down vote up
def save_images(image_path, image_type, data_path, data_name, num_workers):
	"""
	Process all of the image to a numpy array, then store them to a file.
	--------------------
	Arguments:
		image_path (str): path points to images.
		image_type (str): "train", "val", "trainval", or "test".
		data_path (str): path points to the location which stores images.
		data_name (str): name of stored file.
		num_workers (int): number of threads used to load images.
	"""
	dataset = h5py.File(os.path.join(data_path, "%s_%s.h5" % (data_name, image_type)), "w")

	q = queue.Queue()
	images_idx = {}
	images_path = []
	lock = Lock()
	for data in folder_map[image_type]:
		folder = os.path.join(image_path, data)
		images_path.extend(glob.glob(folder+"/*"))
	pattern = re.compile(r"_([0-9]+).jpg")

	for i, img_path in enumerate(images_path):
		assert len(pattern.findall(img_path)) == 1, "More than one index found in an image path!"
		idx = int(pattern.findall(img_path)[0])
		images_idx[idx] = i
		q.put((i, img_path))
	assert len(images_idx) == len(images_path), "Duplicated indices are found!"
	images = dataset.create_dataset("images", (len(images_path), 448, 448, 3), dtype=np.uint8)

	def _worker():
		while True:
			i, img_path = q.get()
			if i is None:
				break
			img = cv2.cvtColor((cv2.resize(cv2.imread(img_path, cv2.CV_LOAD_IMAGE_COLOR), (448, 448))), 
				cv2.COLOR_BGR2RGB)

			with lock:
				if i % 1000 == 0:
					print("processing %i/%i" % (i, len(images_path)))
				images[i] = img
			q.task_done()

	for _ in range(num_workers):
		thread = Thread(target=_worker)
		thread.daemon = True
		thread.start()
	q.join()

	print("Terminating threads...")
	for _ in range(2*num_workers):
		q.put((None, None))

	torch.save(images_idx, os.path.join(data_path, "%s_%s.pt" % (data_name, image_type)))
	dataset.close()
	print("Finish saving images...")