本文整理匯總了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
# --------------------------------------------
示例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)
示例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)
示例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)
示例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
示例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
####################
示例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
示例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.
示例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
示例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
示例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
示例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
示例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)
示例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 = ///////////////////////////////// #
示例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)})