当前位置: 首页>>代码示例>>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;未经允许,请勿转载。