當前位置: 首頁>>代碼示例>>Python>>正文


Python cv2.IMREAD_UNCHANGED屬性代碼示例

本文整理匯總了Python中cv2.IMREAD_UNCHANGED屬性的典型用法代碼示例。如果您正苦於以下問題:Python cv2.IMREAD_UNCHANGED屬性的具體用法?Python cv2.IMREAD_UNCHANGED怎麽用?Python cv2.IMREAD_UNCHANGED使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在cv2的用法示例。


在下文中一共展示了cv2.IMREAD_UNCHANGED屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: imread_uint

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import IMREAD_UNCHANGED [as 別名]
def imread_uint(path, n_channels=3):
    #  input: path
    # output: HxWx3(RGB or GGG), or HxWx1 (G)
    if n_channels == 1:
        img = cv2.imread(path, 0)  # cv2.IMREAD_GRAYSCALE
        img = np.expand_dims(img, axis=2)  # HxWx1
    elif n_channels == 3:
        img = cv2.imread(path, cv2.IMREAD_UNCHANGED)  # BGR or G
        if img.ndim == 2:
            img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)  # GGG
        else:
            img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)  # RGB
    return img


# --------------------------------------------
# matlab's imwrite
# -------------------------------------------- 
開發者ID:cszn,項目名稱:KAIR,代碼行數:20,代碼來源:utils_image.py

示例2: motion_blur

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import IMREAD_UNCHANGED [as 別名]
def motion_blur(x, severity=1):
    c = [(10, 3), (15, 5), (15, 8), (15, 12), (20, 15)][severity - 1]

    output = BytesIO()
    x.save(output, format='PNG')
    x = MotionImage(blob=output.getvalue())

    x.motion_blur(radius=c[0], sigma=c[1], angle=np.random.uniform(-45, 45))

    x = cv2.imdecode(np.fromstring(x.make_blob(), np.uint8),
                     cv2.IMREAD_UNCHANGED)

    if x.shape != (224, 224):
        return np.clip(x[..., [2, 1, 0]], 0, 255)  # BGR to RGB
    else:  # greyscale to RGB
        return np.clip(np.array([x, x, x]).transpose((1, 2, 0)), 0, 255) 
開發者ID:hendrycks,項目名稱:robustness,代碼行數:18,代碼來源:corruptions.py

示例3: motion_blur

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import IMREAD_UNCHANGED [as 別名]
def motion_blur(x, severity=1):
    c = [(10,1), (10,1.5), (10,2), (10,2.5), (12,3)][severity - 1]

    output = BytesIO()
    x.save(output, format='PNG')
    x = MotionImage(blob=output.getvalue())

    x.motion_blur(radius=c[0], sigma=c[1], angle=np.random.uniform(-45, 45))

    x = cv2.imdecode(np.fromstring(x.make_blob(), np.uint8),
                     cv2.IMREAD_UNCHANGED)

    if x.shape != (64, 64):
        return np.clip(x[..., [2, 1, 0]], 0, 255)  # BGR to RGB
    else:  # greyscale to RGB
        return np.clip(np.array([x, x, x]).transpose((1, 2, 0)), 0, 255) 
開發者ID:hendrycks,項目名稱:robustness,代碼行數:18,代碼來源:make_tinyimagenet_c.py

示例4: motion_blur

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import IMREAD_UNCHANGED [as 別名]
def motion_blur(x, severity=1):
    c = [(12,4), (17,6), (17, 9), (17,13), (22,16)][severity - 1]

    output = BytesIO()
    x.save(output, format='PNG')
    x = MotionImage(blob=output.getvalue())

    x.motion_blur(radius=c[0], sigma=c[1], angle=np.random.uniform(-45, 45))

    x = cv2.imdecode(np.fromstring(x.make_blob(), np.uint8),
                     cv2.IMREAD_UNCHANGED)

    if x.shape != (299, 299):
        return np.clip(x[..., [2, 1, 0]], 0, 255)  # BGR to RGB
    else:  # greyscale to RGB
        return np.clip(np.array([x, x, x]).transpose((1, 2, 0)), 0, 255) 
開發者ID:hendrycks,項目名稱:robustness,代碼行數:18,代碼來源:make_imagenet_c_inception.py

示例5: imfrombytes

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import IMREAD_UNCHANGED [as 別名]
def imfrombytes(content, flag='color'):
        """Read an image from bytes.

        Args:
            content (bytes): Image bytes got from files or other streams.
            flag (str): Same as :func:`imread`.

        Returns:
            ndarray: Loaded image array.
        """
        imread_flags = {
            'color': cv2.IMREAD_COLOR,
            'grayscale': cv2.IMREAD_GRAYSCALE,
            'unchanged': cv2.IMREAD_UNCHANGED
        }
        img_np = np.fromstring(content, np.uint8)
        flag = imread_flags[flag] if isinstance(flag, str) else flag
        img = cv2.imdecode(img_np, flag)
        return img 
開發者ID:openseg-group,項目名稱:openseg.pytorch,代碼行數:21,代碼來源:image_helper.py

示例6: read_img

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import IMREAD_UNCHANGED [as 別名]
def read_img(env, path, size=None):
    '''read image by cv2 or from lmdb
    return: Numpy float32, HWC, BGR, [0,1]'''
    if env is None:  # img
        img = cv2.imread(path, cv2.IMREAD_UNCHANGED)
    else:
        img = _read_img_lmdb(env, path, size)
    img = img.astype(np.float32) / 255.
    if img.ndim == 2:
        img = np.expand_dims(img, axis=2)
    # some images have 4 channels
    if img.shape[2] > 3:
        img = img[:, :, :3]
    return img


####################
# image processing
# process on numpy image
#################### 
開發者ID:xinntao,項目名稱:BasicSR,代碼行數:22,代碼來源:util.py

示例7: open_image

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import IMREAD_UNCHANGED [as 別名]
def open_image(path):
	""" Opens an image using OpenCV given the file path.
	:param path: the file path of the image
	:return: the image in RGB format as numpy array of floats normalized to range between 0.0 - 1.0
	"""
	flags = cv2.IMREAD_UNCHANGED+cv2.IMREAD_ANYDEPTH+cv2.IMREAD_ANYCOLOR
	path = str(path)
	if not os.path.exists(path):
		raise OSError(f'No such file or directory: {path}')
	elif os.path.isdir(path):
		raise OSError(f'Is a directory: {path}')
	else:
		try:
			im = cv2.imread(str(path), flags).astype(np.float32)/255
			if im is None: raise OSError(f'File not recognized by opencv: {path}')
			return cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
		except Exception as e:
			raise OSError(f'Error handling image at: {path}') from e 
開發者ID:alecrubin,項目名稱:pytorch-serverless,代碼行數:20,代碼來源:utils.py

示例8: get_image_and_mask

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import IMREAD_UNCHANGED [as 別名]
def get_image_and_mask(img_location, gray_flag):

    # Load image from file with alpha channel (UNCHANGED flag). If an alpha
    # channel does not exist, just return the base image.
    img = cv2.imread(img_location, cv2.IMREAD_UNCHANGED)
    if img.shape[2] <= 3:
        return img, None

    # Create an alpha channel matrix  with values between 0-255. Then
    # threshold the alpha channel to create a binary mask.
    channels = cv2.split(img)
    mask = np.array(channels[3])
    _, mask = cv2.threshold(mask, 250, 255, cv2.THRESH_BINARY)

    # Convert image and mask to grayscale or BGR based on input flag.
    if gray_flag:
        img = cv2.cvtColor(img, cv2.COLOR_BGRA2GRAY)
    else:
        img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
        mask = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)

    return img, mask


# Resize an image and mask based on an input scale ratio. 
開發者ID:jpnaterer,項目名稱:smashscan,代碼行數:27,代碼來源:util.py

示例9: next_batch

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import IMREAD_UNCHANGED [as 別名]
def next_batch(self, size):
    '''
      Return size items (wraps around if the last elements are less than a
      batch size. Be careful with this for evaluation)
    '''
    # different if images are being buffered or not
    images = []
    labels = []
    names = []
    if self.buff:
      for i in range(0, size):
        images.append(self.img_q.get())  # blocking
        labels.append(self.lbl_q.get())  # blocking
        names.append(self.name_q.get())  # blocking
    else:
      for i in range(0, size):
        img = cv2.imread(self.images[self.idx], cv2.IMREAD_UNCHANGED)
        lbl = cv2.imread(self.labels[self.idx], 0)
        images.append(img)
        labels.append(lbl)
        names.append(os.path.basename(self.images[self.idx]))
        self.idx += 1
        if self.idx == self.num_examples:
          self.idx = 0
    return images, labels, names 
開發者ID:PRBonn,項目名稱:bonnet,代碼行數:27,代碼來源:abstract_dataset.py

示例10: predict_mask

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import IMREAD_UNCHANGED [as 別名]
def predict_mask(img, sess, input, output, FLAGS, DATA):
  # open image
  cvim = cv2.imread(img, cv2.IMREAD_UNCHANGED)
  if cvim is None:
    print("No image to open for ", img)
    return
  # predict mask from image
  start = time.time()
  mask = sess.run(output, feed_dict={input: [cvim]})
  print("Prediction for img ", img, ". Elapsed: ", time.time() - start, "s")
  # change to color
  color_mask = util.prediction_to_color(
      mask[0, :, :], DATA["label_remap"], DATA["color_map"])

  cv2.imwrite(FLAGS.log + "/" + os.path.basename(img), color_mask)

  if FLAGS.verbose:
    # show me the image
    # first, mix with image
    im, transparent_mask = util.transparency(cvim, color_mask)
    all_img = np.concatenate((im, transparent_mask, color_mask), axis=1)
    util.im_tight_plt(all_img)
    util.im_block()

  return 
開發者ID:PRBonn,項目名稱:bonnet,代碼行數:27,代碼來源:cnn_use_pb.py

示例11: predict_code

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import IMREAD_UNCHANGED [as 別名]
def predict_code(img, sess, input, output, FLAGS):
  # predict feature map from image
  # open image
  cvim = cv2.imread(img, cv2.IMREAD_UNCHANGED)
  if cvim is None:
    print("No image to open for ", img)
    return

  # predict code from image
  print("Prediction for img ", img)
  code = sess.run(output, feed_dict={input: [cvim]})

  # reshape code to single dimension
  reshaped_code = np.reshape(code, (1, -1))
  print("Shape", reshaped_code.shape)

  # save code to text file
  filename = FLAGS.log + "/" + \
      os.path.splitext(os.path.basename(img))[0] + ".txt"
  print("Saving feature map to: ", filename)
  np.savetxt(filename, reshaped_code, fmt="%.8f", delimiter=" ")

  return 
開發者ID:PRBonn,項目名稱:bonnet,代碼行數:25,代碼來源:cnn_use_pb.py

示例12: predict_code

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import IMREAD_UNCHANGED [as 別名]
def predict_code(img, net, FLAGS):
  # predict feature map from image
  # open image
  cvim = cv2.imread(img, cv2.IMREAD_UNCHANGED)
  if cvim is None:
    print("No image to open for ", img)
    return
  # predict mask from image
  start = time.time()
  code = net.predict_code(cvim, path=FLAGS.path + '/' +
                          FLAGS.model, verbose=FLAGS.verbose)
  print("Prediction for img ", img, ". Elapsed: ", time.time() - start, "s")

  # reshape code to single dimension
  reshaped_code = np.reshape(code, (1, -1))
  # print("Shape", reshaped_code.shape)

  # save code to text file
  filename = FLAGS.log + "/" + \
      os.path.splitext(os.path.basename(img))[0] + ".txt"
  print("Saving feature map to: ", filename)
  np.savetxt(filename, reshaped_code, fmt="%.8f", delimiter=" ")

  return 
開發者ID:PRBonn,項目名稱:bonnet,代碼行數:26,代碼來源:cnn_use.py

示例13: read

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import IMREAD_UNCHANGED [as 別名]
def read(filepath_or_buffer: typing.Union[str, io.BytesIO]):
    """Read a file into an image object

    Args:
        filepath_or_buffer: The path to the file, a URL, or any object
            with a `read` method (such as `io.BytesIO`)
    """
    if isinstance(filepath_or_buffer, np.ndarray):
        return filepath_or_buffer
    if hasattr(filepath_or_buffer, 'read'):
        image = np.asarray(bytearray(filepath_or_buffer.read()), dtype=np.uint8)
        image = cv2.imdecode(image, cv2.IMREAD_UNCHANGED)
    elif isinstance(filepath_or_buffer, str):
        if validators.url(filepath_or_buffer):
            return read(urllib.request.urlopen(filepath_or_buffer))
        assert os.path.isfile(filepath_or_buffer), \
            'Could not find image at path: ' + filepath_or_buffer
        image = cv2.imread(filepath_or_buffer)
    return cv2.cvtColor(image, cv2.COLOR_BGR2RGB) 
開發者ID:faustomorales,項目名稱:keras-ocr,代碼行數:21,代碼來源:tools.py

示例14: get_datum

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import IMREAD_UNCHANGED [as 別名]
def get_datum(self, idx):
        taxonomy_name = self.file_list[idx]['taxonomy_name']
        sample_name = self.file_list[idx]['sample_name']
        rendering_image_path = self.file_list[idx]['rendering_image']
        bounding_box = self.file_list[idx]['bounding_box']
        volume_path = self.file_list[idx]['volume']

        # Get data of rendering images
        rendering_image = cv2.imread(rendering_image_path, cv2.IMREAD_UNCHANGED).astype(np.float32) / 255.

        if len(rendering_image.shape) < 3:
            print('[WARN] %s It seems the image file %s is grayscale.' % (dt.now(), rendering_image_path))
            rendering_image = np.stack((rendering_image, ) * 3, -1)

        # Get data of volume
        with open(volume_path, 'rb') as f:
            volume = utils.binvox_rw.read_as_3d_array(f)
            volume = volume.data.astype(np.float32)

        return taxonomy_name, sample_name, np.asarray([rendering_image]), volume, bounding_box


# //////////////////////////////// = End of Pascal3dDataset Class Definition = ///////////////////////////////// # 
開發者ID:hzxie,項目名稱:Pix2Vox,代碼行數:25,代碼來源:data_loaders.py

示例15: __getitem__

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import IMREAD_UNCHANGED [as 別名]
def __getitem__(self, item):
        img = cv2.imread(self.__image_pathes[item]['data'])
        return self.__aug({'data': img,
                           'target': cv2.imread(self.__image_pathes[item]['target'], cv2.IMREAD_UNCHANGED)}) 
開發者ID:toodef,項目名稱:neural-pipeline,代碼行數:6,代碼來源:img_segmentation.py


注:本文中的cv2.IMREAD_UNCHANGED屬性示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。