本文整理汇总了Python中cv2.COLOR_RGB2BGR属性的典型用法代码示例。如果您正苦于以下问题:Python cv2.COLOR_RGB2BGR属性的具体用法?Python cv2.COLOR_RGB2BGR怎么用?Python cv2.COLOR_RGB2BGR使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在模块cv2的用法示例。

在下文中一共展示了cv2.COLOR_RGB2BGR属性的30个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: __get_annotation__

​点赞 7

# 需要导入模块: import cv2 [as 别名]

# 或者: from cv2 import COLOR_RGB2BGR [as 别名]

def __get_annotation__(self, mask, image=None):

_, contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

segmentation = []

for contour in contours:

# Valid polygons have >= 6 coordinates (3 points)

if contour.size >= 6:

segmentation.append(contour.flatten().tolist())

RLEs = cocomask.frPyObjects(segmentation, mask.shape[0], mask.shape[1])

RLE = cocomask.merge(RLEs)

# RLE = cocomask.encode(np.asfortranarray(mask))

area = cocomask.area(RLE)

[x, y, w, h] = cv2.boundingRect(mask)

if image is not None:

image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)

cv2.drawContours(image, contours, -1, (0,255,0), 1)

cv2.rectangle(image,(x,y),(x+w,y+h), (255,0,0), 2)

cv2.imshow("", image)

cv2.waitKey(1)

return segmentation, [x, y, w, h], area

开发者ID:hazirbas,项目名称:coco-json-converter,代码行数:25,

示例2: undistort_images

​点赞 6

# 需要导入模块: import cv2 [as 别名]

# 或者: from cv2 import COLOR_RGB2BGR [as 别名]

def undistort_images(src, dst):

"""

undistort the images in src folder to dst folder

"""

# load dst, mtx

pickle_file = open("../camera_cal/camera_cal.p", "rb")

dist_pickle = pickle.load(pickle_file)

mtx = dist_pickle["mtx"]

dist = dist_pickle["dist"]

pickle_file.close()

# loop the image folder

image_files = glob.glob(src+"*.jpg")

for idx, file in enumerate(image_files):

print(file)

img = mpimg.imread(file)

image_dist = cv2.undistort(img, mtx, dist, None, mtx)

file_name = file.split("\\")[-1]

print(file_name)

out_image = dst+file_name

print(out_image)

image_dist = cv2.cvtColor(image_dist, cv2.COLOR_RGB2BGR)

cv2.imwrite(out_image, image_dist)

开发者ID:ChengZhongShen,项目名称:Advanced_Lane_Lines,代码行数:25,

示例3: wrap_images

​点赞 6

# 需要导入模块: import cv2 [as 别名]

# 或者: from cv2 import COLOR_RGB2BGR [as 别名]

def wrap_images(src, dst):

"""

apply the wrap to images

"""

# load M, Minv

img_size = (1280, 720)

pickle_file = open("../helper/trans_pickle.p", "rb")

trans_pickle = pickle.load(pickle_file)

M = trans_pickle["M"]

Minv = trans_pickle["Minv"]

# loop the file folder

image_files = glob.glob(src+"*.jpg")

for idx, file in enumerate(image_files):

print(file)

img = mpimg.imread(file)

image_wraped = cv2.warpPerspective(img, M, img_size, flags=cv2.INTER_LINEAR)

file_name = file.split("\\")[-1]

print(file_name)

out_image = dst+file_name

print(out_image)

# no need to covert RGB to BGR since 3 channel is same

image_wraped = cv2.cvtColor(image_wraped, cv2.COLOR_RGB2BGR)

cv2.imwrite(out_image, image_wraped)

开发者ID:ChengZhongShen,项目名称:Advanced_Lane_Lines,代码行数:25,

示例4: test

​点赞 6

# 需要导入模块: import cv2 [as 别名]

# 或者: from cv2 import COLOR_RGB2BGR [as 别名]

def test():

pickle_file = open("trans_pickle.p", "rb")

trans_pickle = pickle.load(pickle_file)

M = trans_pickle["M"]

Minv = trans_pickle["Minv"]

img_size = (1280, 720)

image_files = glob.glob("../output_images/undistort/*.jpg")

for idx, file in enumerate(image_files):

print(file)

img = mpimg.imread(file)

warped = cv2.warpPerspective(img, M, img_size, flags=cv2.INTER_LINEAR)

file_name = file.split("\\")[-1]

print(file_name)

out_image = "../output_images/perspect_trans/"+file_name

print(out_image)

# convert to opencv BGR format

warped = cv2.cvtColor(warped, cv2.COLOR_RGB2BGR)

cv2.imwrite(out_image, warped)

开发者ID:ChengZhongShen,项目名称:Advanced_Lane_Lines,代码行数:22,

示例5: save_result

​点赞 6

# 需要导入模块: import cv2 [as 别名]

# 或者: from cv2 import COLOR_RGB2BGR [as 别名]

def save_result(self):

path = os.path.abspath(self.image_file)

path, ext = os.path.splitext(path)

suffix = datetime.datetime.now().strftime("%y%m%d_%H%M%S")

save_path = "_".join([path, self.method, suffix])

print('saving result to \n' % save_path)

if not os.path.exists(save_path):

os.mkdir(save_path)

np.save(os.path.join(save_path, 'im_l.npy'), self.model.img_l)

np.save(os.path.join(save_path, 'im_ab.npy'), self.im_ab0)

np.save(os.path.join(save_path, 'im_mask.npy'), self.im_mask0)

result_bgr = cv2.cvtColor(self.result, cv2.COLOR_RGB2BGR)

mask = self.im_mask0.transpose((1, 2, 0)).astype(np.uint8) * 255

cv2.imwrite(os.path.join(save_path, 'input_mask.png'), mask)

cv2.imwrite(os.path.join(save_path, 'ours.png'), result_bgr)

cv2.imwrite(os.path.join(save_path, 'ours_fullres.png'), self.model.get_img_fullres()[:, :, ::-1])

cv2.imwrite(os.path.join(save_path, 'input_fullres.png'), self.model.get_input_img_fullres()[:, :, ::-1])

cv2.imwrite(os.path.join(save_path, 'input.png'), self.model.get_input_img()[:, :, ::-1])

cv2.imwrite(os.path.join(save_path, 'input_ab.png'), self.model.get_sup_img()[:, :, ::-1])

开发者ID:junyanz,项目名称:interactive-deep-colorization,代码行数:25,

示例6: plotResults

​点赞 6

# 需要导入模块: import cv2 [as 别名]

# 或者: from cv2 import COLOR_RGB2BGR [as 别名]

def plotResults(fname, result_list):

columm = []

for fig in result_list:

shape = fig.shape

fig = fig.numpy()

row = []

for idx in range(shape[0]):

item = fig[idx, :, :, :]

if item.shape[2] == 1:

item = np.concatenate([item, item, item], axis=2)

item = cv2.cvtColor(cv2.resize(item, (128, 128)), cv2.COLOR_RGB2BGR)

row.append(item)

row = np.concatenate(row, axis=1)

columm.append(row)

columm = np.concatenate(columm, axis=0)

img = np.uint8(columm * 255)

cv2.imwrite(fname, img)

############################################################

# Deep Tree Network

############################################################

开发者ID:yaojieliu,项目名称:CVPR2019-DeepTreeLearningForZeroShotFaceAntispoofing,代码行数:24,

示例7: start

​点赞 6

# 需要导入模块: import cv2 [as 别名]

# 或者: from cv2 import COLOR_RGB2BGR [as 别名]

def start(self):

"""

启动程序

:return:

"""

self.console("程序启动成功.")

self.init_mask()

while self.listener:

frame = self.read_data()

frame = resize(frame, width=self.max_width)

img_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

rects = self.detector(img_gray, 0)

faces = self.orientation(rects, img_gray)

draw_img = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))

if self.doing:

self.drawing(draw_img, faces)

self.animation_time += self.speed

self.save_data(draw_img)

if self.animation_time > self.duration:

self.doing = False

self.animation_time = 0

else:

frame = cv2.cvtColor(np.asarray(draw_img), cv2.COLOR_RGB2BGR)

cv2.imshow("hello mask", frame)

self.listener_keys()

开发者ID:tomoncle,项目名称:face-detection-induction-course,代码行数:27,

示例8: train_generator

​点赞 6

# 需要导入模块: import cv2 [as 别名]

# 或者: from cv2 import COLOR_RGB2BGR [as 别名]

def train_generator(self, image_generator, mask_generator):

# cv2.namedWindow('show', 0)

# cv2.resizeWindow('show', 1280, 640)

while True:

image = next(image_generator)

mask = next(mask_generator)

label = self.make_regressor_label(mask).astype(np.float32)

# print (image.dtype, label.dtype)

# print (image.shape, label.shape)

# exit()

# cv2.imshow('show', image[0].astype(np.uint8))

# cv2.imshow('label', label[0].astype(np.uint8))

# mask = self.select_labels(mask)

# print (image.shape)

# print (mask.shape)

# image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)

# mask = (mask.astype(np.float32)*255/33).astype(np.uint8)

# mask_color = cv2.applyColorMap(mask, cv2.COLORMAP_JET)

# print (mask_color.shape)

# show = cv2.addWeighted(image, 0.5, mask_color, 0.5, 0.0)

# cv2.imshow("show", show)

# key = cv2.waitKey()

# if key == 27:

# exit()

yield (image, label)

开发者ID:dhkim0225,项目名称:keras-image-segmentation,代码行数:27,

示例9: return_left_camera_image

​点赞 6

# 需要导入模块: import cv2 [as 别名]

# 或者: from cv2 import COLOR_RGB2BGR [as 别名]

def return_left_camera_image(self, mode='RGB'):

"""Return a numpy array with the LEFT camera image

@param mode the image to return (default RGB)

RGB: Red Green Blue image

BGR: Blue Green Red (OpenCV)

GRAY: Grayscale image

"""

self.port_left_camera.read(self.yarp_image)

if(mode=='BGR'):

return cv2.cvtColor(self.img_array, cv2.COLOR_RGB2BGR)

elif(mode=='RGB'):

return self.img_array

elif(mode=='GRAY'):

return cv2.cvtColor(self.img_array, cv2.COLOR_BGR2GRAY)

else:

return self.img_array

开发者ID:mpatacchiola,项目名称:pyERA,代码行数:19,

示例10: return_right_camera_image

​点赞 6

# 需要导入模块: import cv2 [as 别名]

# 或者: from cv2 import COLOR_RGB2BGR [as 别名]

def return_right_camera_image(self, mode='RGB'):

"""Return a numpy array with the RIGHT camera image

@param mode the image to return (default RGB)

RGB: Red Green Blue image

BGR: Blue Green Red (OpenCV)

GRAY: Grayscale image

"""

self.port_right_camera.read(self.yarp_image)

if(mode=='BGR'):

return cv2.cvtColor(self.img_array, cv2.COLOR_RGB2BGR)

elif(mode=='RGB'):

return self.img_array

elif(mode=='GRAY'):

return cv2.cvtColor(self.img_array, cv2.COLOR_BGR2GRAY)

else:

return self.img_array

开发者ID:mpatacchiola,项目名称:pyERA,代码行数:19,

示例11: mx2tfrecords_old

​点赞 6

# 需要导入模块: import cv2 [as 别名]

# 或者: from cv2 import COLOR_RGB2BGR [as 别名]

def mx2tfrecords_old(imgidx, imgrec, args):

output_path = os.path.join(args.tfrecords_file_path, 'tran.tfrecords')

writer = tf.python_io.TFRecordWriter(output_path)

for i in imgidx:

img_info = imgrec.read_idx(i)

header, img = mx.recordio.unpack(img_info)

encoded_jpg_io = io.BytesIO(img)

image = PIL.Image.open(encoded_jpg_io)

np_img = np.array(image)

img = cv2.cvtColor(np_img, cv2.COLOR_RGB2BGR)

img_raw = img.tobytes()

label = int(header.label)

example = tf.train.Example(features=tf.train.Features(feature={

'image_raw': tf.train.Feature(bytes_list=tf.train.BytesList(value=[img_raw])),

"label": tf.train.Feature(int64_list=tf.train.Int64List(value=[label]))

}))

writer.write(example.SerializeToString()) # Serialize To String

if i % 10000 == 0:

print('%d num image processed' % i)

writer.close()

开发者ID:auroua,项目名称:InsightFace_TF,代码行数:22,

示例12: mx2tfrecords

​点赞 6

# 需要导入模块: import cv2 [as 别名]

# 或者: from cv2 import COLOR_RGB2BGR [as 别名]

def mx2tfrecords(imgidx, imgrec, args):

output_path = os.path.join(args.tfrecords_file_path, 'tran.tfrecords')

writer = tf.python_io.TFRecordWriter(output_path)

for i in imgidx:

img_info = imgrec.read_idx(i)

header, img = mx.recordio.unpack(img_info)

encoded_jpg_io = io.BytesIO(img)

image = PIL.Image.open(encoded_jpg_io)

np_img = np.array(image)

img = cv2.cvtColor(np_img, cv2.COLOR_RGB2BGR)

img_raw = img.tobytes()

label = int(header.label)

example = tf.train.Example(features=tf.train.Features(feature={

'image_raw': tf.train.Feature(bytes_list=tf.train.BytesList(value=[img_raw])),

"label": tf.train.Feature(int64_list=tf.train.Int64List(value=[label]))

}))

writer.write(example.SerializeToString()) # Serialize To String

if i % 10000 == 0:

print('%d num image processed' % i)

writer.close()

开发者ID:auroua,项目名称:InsightFace_TF,代码行数:22,

示例13: load_bin

​点赞 6

# 需要导入模块: import cv2 [as 别名]

# 或者: from cv2 import COLOR_RGB2BGR [as 别名]

def load_bin(db_name, image_size, args):

bins, issame_list = pickle.load(open(os.path.join(args.eval_db_path, db_name+'.bin'), 'rb'), encoding='bytes')

data_list = []

for _ in [0,1]:

data = np.empty((len(issame_list)*2, image_size[0], image_size[1], 3))

data_list.append(data)

for i in range(len(issame_list)*2):

_bin = bins[i]

img = mx.image.imdecode(_bin).asnumpy()

img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)

for flip in [0,1]:

if flip == 1:

img = np.fliplr(img)

data_list[flip][i, ...] = img

i += 1

if i % 1000 == 0:

print('loading bin', i)

print(data_list[0].shape)

return data_list, issame_list

开发者ID:auroua,项目名称:InsightFace_TF,代码行数:21,

示例14: colorize

​点赞 6

# 需要导入模块: import cv2 [as 别名]

# 或者: from cv2 import COLOR_RGB2BGR [as 别名]

def colorize(self, label_map, image_canvas=None):

height, width = label_map.shape

color_dst = np.zeros((height, width, 3), dtype=np.uint8)

color_list = self.configer.get('details', 'color_list')

for i in range(self.configer.get('data', 'num_classes')):

color_dst[label_map == i] = color_list[i % len(color_list)]

color_img_rgb = np.array(color_dst, dtype=np.uint8)

color_img_bgr = cv2.cvtColor(color_img_rgb, cv2.COLOR_RGB2BGR)

if image_canvas is not None:

image_canvas = cv2.addWeighted(image_canvas, 0.6, color_img_bgr, 0.4, 0)

return image_canvas

else:

return color_img_bgr

开发者ID:openseg-group,项目名称:openseg.pytorch,代码行数:18,

示例15: drawrect

​点赞 6

# 需要导入模块: import cv2 [as 别名]

# 或者: from cv2 import COLOR_RGB2BGR [as 别名]

def drawrect(img, rect, text):

cv2.rectangle(img, tuple(rect[:2]), tuple(rect[2:]), (10,250,10), 2, 1)

x, y = rect[:2]

def cv2ImgAddText(img, text, left, top, textColor=(0, 255, 0), textSize=20):

from PIL import Image, ImageDraw, ImageFont

img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))

draw = ImageDraw.Draw(img)

fontText = ImageFont.truetype( "font/simsun.ttc", textSize, encoding="utf-8")

draw.text((left, top), text, textColor, font=fontText)

return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)

import re

if re.findall('[\u4e00-\u9fa5]', text):

img = cv2ImgAddText(img, text, x, y-12, (10,10,250), 12) # 如果存在中文则使用这种方式绘制文字

else:

cv2.putText(img, text, (x,y), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (10,10,250), 1)

return img

开发者ID:cilame,项目名称:vrequest,代码行数:18,

示例16: preprocess_inception

​点赞 6

# 需要导入模块: import cv2 [as 别名]

# 或者: from cv2 import COLOR_RGB2BGR [as 别名]

def preprocess_inception(image_name):

image = cv2.imread(image_name)

if image is None:

return None

image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

target_size = 256

crop_size = 224

im_size_min = np.min(image.shape[0:2])

im_scale = float(target_size) / float(im_size_min)

image = cv2.resize(image, None, None, fx=im_scale, fy=im_scale, interpolation=cv2.INTER_LINEAR)

height = image.shape[0]

width = image.shape[1]

x = int((width - crop_size) / 2)

y = int((height - crop_size) / 2)

image = image[y: y + crop_size, x: x + crop_size]

save_dir = '/nfs.yoda/xiaolonw/judy_folder/transfer/debug/'

if not os.path.exists(save_dir):

os.makedirs(save_dir)

cv2.imwrite(save_dir + '1.jpg', cv2.cvtColor(image, cv2.COLOR_RGB2BGR))

image = image.astype(np.float32)

image /= 255

image = 2 * image - 1

image = image[np.newaxis, :, :, :]

return image

开发者ID:JudyYe,项目名称:zero-shot-gcn,代码行数:27,

示例17: add_datum

​点赞 6

# 需要导入模块: import cv2 [as 别名]

# 或者: from cv2 import COLOR_RGB2BGR [as 别名]

def add_datum(self, *inds, **datum_dict):

other_dict = dict([item for item in datum_dict.items() if not item[0].endswith('image')])

super(ImageDataContainer, self).add_datum(*inds, **other_dict)

image_dict = dict([item for item in datum_dict.items() if item[0].endswith('image')])

for image_name, image in image_dict.items():

if image_name in self.datum_shapes_dict and self.datum_shapes_dict[image_name] != image.shape:

raise ValueError('unable to add datum %s with shape %s since the shape %s was expected' %

(image_name, image.shape, self.datum_shapes_dict[image_name]))

self.datum_shapes_dict[image_name] = image.shape

image_fname = self._get_image_fname(*(inds + (image_name,)))

if image.dtype == np.uint8:

if image.ndim == 3 and image.shape[2] == 3:

image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)

else:

image = math_utils.pack_image(image)

cv2.imwrite(image_fname, image, [int(cv2.IMWRITE_JPEG_QUALITY), 100])

开发者ID:alexlee-gk,项目名称:visual_dynamics,代码行数:18,

示例18: do_demo

​点赞 6

# 需要导入模块: import cv2 [as 别名]

# 或者: from cv2 import COLOR_RGB2BGR [as 别名]

def do_demo(self, folder):

save_dir = os.path.join(self.output_dir, 'predictions')

if not os.path.isdir(save_dir):

os.makedirs(save_dir)

folder_dir = os.path.join(self.dataset_dir, folder, 'image_02', 'data', '*.*')

images_files = sorted(glob.glob(folder_dir))

print(f'doing demo on {self.demo_set}... ')

print(f'saving prediction to {save_dir}...')

for i, img_path in enumerate(images_files):

img = cv2.cvtColor(cv2.imread(img_path), cv2.COLOR_BGR2RGB)

img = cv2.resize(img, (self.params.input_w, self.params.input_h))

img_input = tf.expand_dims(tf.convert_to_tensor(img, tf.float32) / 255., 0)

outputs = self.val_step(img_input)

disp = np.squeeze(outputs['disparity0'].numpy())

disp = visualize_colormap(disp)

save_path = os.path.join(save_dir, f'{i}.png')

big_image = np.zeros(shape=(self.params.input_h * 2, self.params.input_w, 3))

big_image[:self.params.input_h, ...] = img

big_image[self.params.input_h:, ...] = disp

cv2.imwrite(save_path, cv2.cvtColor(big_image.astype(np.uint8), cv2.COLOR_RGB2BGR))

print("\n-> Done!\n")

开发者ID:darylclimb,项目名称:cvml_project,代码行数:26,

示例19: generate

​点赞 6

# 需要导入模块: import cv2 [as 别名]

# 或者: from cv2 import COLOR_RGB2BGR [as 别名]

def generate(path):

global cur_rgb_image

if cur_rgb_image is not None:

print('process......')

el_img, er_img, angle, re_angle, os_l, os_r = get_input_from_image()

el, er = get_output_from_sess(el_img, er_img, angle, re_angle)

new_image = np.copy(cur_rgb_image)

new_image = helper.replace(new_image, el, os_l)

rgb_new_image = helper.replace(new_image, er, os_r)

# bgr_new_image = cv2.cvtColor(rgb_new_image, cv2.COLOR_RGB2BGR)

# cv2.imshow('deepwarp', bgr_new_image)

# if chk_btn.get() == True:

# rgb_new_image = cv2.medianBlur(rgb_new_image, 3)

global label_img

img_wapper = ImageTk.PhotoImage(Image.fromarray(rgb_new_image))

label_img.configure(image=img_wapper)

label_img.image = img_wapper

return rgb_new_image

else:

print('no image......')

return None

开发者ID:BlueWinters,项目名称:DeepWarp,代码行数:26,

示例20: preserve_colors_np

​点赞 6

# 需要导入模块: import cv2 [as 别名]

# 或者: from cv2 import COLOR_RGB2BGR [as 别名]

def preserve_colors_np(style_rgb, content_rgb):

coraled = coral_numpy(style_rgb/255., content_rgb/255.)

coraled = np.uint8(np.clip(coraled, 0, 1) * 255.)

return coraled

# def preserve_colors_pytorch(style_rgb, content_rgb):

# coraled = coral_pytorch(style_rgb/255., content_rgb/255.)

# coraled = np.uint8(np.clip(coraled, 0, 1) * 255.)

# return coraled

# def preserve_colors_color_transfer(style_rgb, content_rgb):

# style_bgr = cv2.cvtColor(style_rgb, cv2.COLOR_RGB2BGR)

# content_bgr = cv2.cvtColor(content_rgb, cv2.COLOR_RGB2BGR)

# transferred = color_transfer(content_bgr, style_bgr)

# return cv2.cvtColor(transferred, cv2.COLOR_BGR2RGB)

### Video/Webcam helpers

### Borrowed from https://github.com/jrosebr1/imutils/

开发者ID:eridgd,项目名称:AdaIN-TF,代码行数:20,

示例21: RGB_To_CvBGR

​点赞 6

# 需要导入模块: import cv2 [as 别名]

# 或者: from cv2 import COLOR_RGB2BGR [as 别名]

def RGB_To_CvBGR(img):

return cv2.cvtColor(img,cv2.COLOR_RGB2BGR)

#def saveAsPNG(_2dArray, filename):

# if any([len(row) != len(_2dArray[0]) for row in _2dArray]):

# raise ValueError, "_2dArray should have elements of equal size"

#

# #First row becomes top row of image.

# flat = []; map(flat.extend, reversed(_2dArray))

# #Big-endian, unsigned 32-byte integer.

# buf = b''.join([struct.pack('>I', ((0xffFFff & i32)<<8)|(i32>>24) )

# for i32 in flat]) #Rotate from ARGB to RGBA.

#

# data = write_png(buf, len(_2dArray[0]), len(_2dArray))

# f = open(filename, 'wb')

# f.write(data)

# f.close()

开发者ID:dan59314,项目名称:MNIST-Deep-Learning,代码行数:20,

示例22: inverse_preprocess

​点赞 5

# 需要导入模块: import cv2 [as 别名]

# 或者: from cv2 import COLOR_RGB2BGR [as 别名]

def inverse_preprocess(image):

image = image.numpy().transpose((1,2,0)) * 255

image = image.astype(np.uint8)

if image.shape[2] == 3:

image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)

#pass

return image

开发者ID:HaiyangLiu1997,项目名称:Pytorch-Networks,代码行数:9,

示例23: main

​点赞 5

# 需要导入模块: import cv2 [as 别名]

# 或者: from cv2 import COLOR_RGB2BGR [as 别名]

def main():

args = parser.parse_args()

# Get all image paths

image_paths = [os.path.join(args.image_dir, x) for x in os.listdir(args.image_dir)]

# Change model input shape to accept all size inputs

model = keras.models.load_model('models/generator.h5')

inputs = keras.Input((None, None, 3))

output = model(inputs)

model = keras.models.Model(inputs, output)

# Loop over all images

for image_path in image_paths:

# Read image

low_res = cv2.imread(image_path, 1)

# Convert to RGB (opencv uses BGR as default)

low_res = cv2.cvtColor(low_res, cv2.COLOR_BGR2RGB)

# Rescale to 0-1.

low_res = low_res / 255.0

# Get super resolution image

sr = model.predict(np.expand_dims(low_res, axis=0))[0]

# Rescale values in range 0-255

sr = ((sr + 1) / 2.) * 255

# Convert back to BGR for opencv

sr = cv2.cvtColor(sr, cv2.COLOR_RGB2BGR)

# Save the results:

cv2.imwrite(os.path.join(args.output_dir, os.path.basename(image_path)), sr)

开发者ID:HasnainRaz,项目名称:Fast-SRGAN,代码行数:37,

示例24: images_test_tracker

​点赞 5

# 需要导入模块: import cv2 [as 别名]

# 或者: from cv2 import COLOR_RGB2BGR [as 别名]

def images_test_tracker(src, dst, video, debug_window=False):

'''

test the pipeline on src folder's images

write the result to the dst folder

'''

# create pipeline instance

left = Line()

right = Line()

pipeline = Pipeline(left, right)

# checkif debug_window if turn on

pipeline.debug_window = True if debug_window else False

image_files = glob.glob(src+"*.jpg")

for idx, file in enumerate(image_files):

print("handle on: ", file)

img = mpimg.imread(file)

# use different pipeline according video

if video=="project":

result = pipeline.pipeline(img)

if video == "challenge":

result = pipeline.pipeline_challenge(img)

if video == "harder":

result = pipeline.pipeline_harder(img)

file_name = file.split("\\")[-1]

out_image = dst+file_name

image_dist = cv2.cvtColor(result, cv2.COLOR_RGB2BGR)

cv2.imwrite(out_image, image_dist)

print("processed", pipeline.image_counter, "images")

print("fit_fail Failure: ", pipeline.fit_fail_counter)

print("Search Failure: ", pipeline.search_fail_counter)

print("write the processed image to: ", dst)

##############################################################################

开发者ID:ChengZhongShen,项目名称:Advanced_Lane_Lines,代码行数:39,

示例25: detect_img

​点赞 5

# 需要导入模块: import cv2 [as 别名]

# 或者: from cv2 import COLOR_RGB2BGR [as 别名]

def detect_img(yolo):

while True:

img = input('Input image filename:')

try:

image = Image.open(img)

except:

print('Open Error! Try again!')

continue

else:

r_image = yolo.detect_image(image)

# r_image.show()

opencvImage = cv2.cvtColor(numpy.array(image), cv2.COLOR_RGB2BGR)

cv2.imwrite('pictures/test_result.png',opencvImage)

yolo.close_session()

开发者ID:bing0037,项目名称:keras-yolo3,代码行数:16,

示例26: renderVideo

​点赞 5

# 需要导入模块: import cv2 [as 别名]

# 或者: from cv2 import COLOR_RGB2BGR [as 别名]

def renderVideo(self):

if not self.isRendered:

print("Started Rendering Script %s" % self.scriptno)

imageframe.deleteAllFilesInPath(settings.tempPath)

try:

video_format = standardredditformat.StandardReddit("shit", self.video_settings, self.music_type)

formatted_script = imageframe.parseScript(self.final_script)

newMovie = generatemovie.Movie(video_format, formatted_script,

(self.author, self.scripttitle, self.ups), self.scriptno)

export_location = newMovie.renderVideo()

try:

cv2.imwrite(export_location + "/thumbnail.png", cv2.cvtColor(self.thumbnail, cv2.COLOR_RGB2BGR))

except Exception:

pass

writeTextToFile(export_location + "/description.txt", self.youtube_description)

writeTextToFile(export_location + "/youtubetitle.txt", self.youtube_title)

writeTextToFile(export_location + "/youtubetags.txt", self.youtube_tags)

except Exception as e:

print(e)

print("Sorry, a error occured rendering this video. Skipping it")

self.isRendered = True

self.save()

if settings.exportOffline:

generatorclient.updateUploadDetails(self.scriptno, None, None)

deleteRawSave(self.scriptno)

videoscripts.remove(self)

print("Video Successfully exported offline")

else:

print("VID GEN script %s already rendered" % self.scriptno)

开发者ID:HA6Bots,项目名称:Automatic-Youtube-Reddit-Text-To-Speech-Video-Generator-and-Uploader,代码行数:33,

示例27: change_cv2_draw

​点赞 5

# 需要导入模块: import cv2 [as 别名]

# 或者: from cv2 import COLOR_RGB2BGR [as 别名]

def change_cv2_draw(image,strs,local,sizes,colour):

cv2img = cv2.cvtColor(image,cv2.COLOR_BGR2RGB)

pilimg = Image.fromarray(cv2img)

draw = ImageDraw.Draw(pilimg)

font = ImageFont.truetype("./core/font_lib/Microsoft-Yahei-UI-Light.ttc",sizes,encoding='utf-8')

draw.text(local,strs,colour,font=font)

image = cv2.cvtColor(np.array(pilimg),cv2.COLOR_RGB2BGR)

return image

开发者ID:DataXujing,项目名称:CornerNet-Lite-Pytorch,代码行数:11,

示例28: rec_test

​点赞 5

# 需要导入模块: import cv2 [as 别名]

# 或者: from cv2 import COLOR_RGB2BGR [as 别名]

def rec_test(test_data, n_epochs=0, batch_size=128, output_dir=None):

print('computing reconstruction loss on test images')

rec_imgs = []

imgs = []

costs = []

ntest = len(test_data)

for n in tqdm(range(ntest / batch_size)):

imb = test_data[n * batch_size:(n + 1) * batch_size, ...]

# imb = train_dcgan_utils.transform(xmb, nc=3)

[cost, gx] = _train_p_cost(imb)

costs.append(cost)

ntest = ntest + 1

if n == 0:

utils.print_numpy(imb)

utils.print_numpy(gx)

imgs.append(train_dcgan_utils.inverse_transform(imb, npx=npx, nc=nc))

rec_imgs.append(train_dcgan_utils.inverse_transform(gx, npx=npx, nc=nc))

if output_dir is not None:

# st()

save_samples = np.hstack(np.concatenate(imgs, axis=0))

save_recs = np.hstack(np.concatenate(rec_imgs, axis=0))

save_comp = np.vstack([save_samples, save_recs])

mean_cost = np.mean(costs)

txt = 'epoch = %3.3d, cost = %3.3f' % (n_epochs, mean_cost)

width = save_comp.shape[1]

save_f = (save_comp * 255).astype(np.uint8)

html.save_image([save_f], [''], header=txt, width=width, cvt=True)

html.save()

save_cvt = cv2.cvtColor(save_f, cv2.COLOR_RGB2BGR)

cv2.imwrite(os.path.join(rec_dir, 'rec_epoch_%5.5d.png' % n_epochs), save_cvt)

return mean_cost

开发者ID:junyanz,项目名称:iGAN,代码行数:39,

示例29: photo_read

​点赞 5

# 需要导入模块: import cv2 [as 别名]

# 或者: from cv2 import COLOR_RGB2BGR [as 别名]

def photo_read(self, path, num):

# 使用dlib自带的frontal_face_detector作为我们的特征提取器

detector = align_dlib.AlignDlib(self.PREDICTOR_PATH)

path = self.input_dir + '/' + path

print(path + " 正在处理...")

name_file = str(num) + '_' + path.split('/')[-1]

name_file = self.output_dir + '/' + name_file

# 如果不存在目录 就创造目录

if not os.path.exists(name_file):

os.makedirs(name_file)

index = 1

for filename in os.listdir(path):

if filename.endswith('.jpg'):

img_path = path + '/' + filename

print(img_path)

# 从文件读取图片

img_bgr = cv2.imread(img_path) # 从文件读取bgr图片

img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB) # 转为RGB图片

face_align = detector.align(size, img_rgb)

if face_align is None:

pass

else:

face_align = cv2.cvtColor(face_align, cv2.COLOR_RGB2BGR) # 转为BGR图片

# 保存图片

cv2.imwrite(name_file + '/' + str(index) + '.jpg', face_align)

index += 1

开发者ID:yeziyang1992,项目名称:Python-Tensorflow-Face-v2.0,代码行数:29,

示例30: get_one_image

​点赞 5

# 需要导入模块: import cv2 [as 别名]

# 或者: from cv2 import COLOR_RGB2BGR [as 别名]

def get_one_image(self, x, detector):

path_name_x = self.path + self.path_array[x-1]

try:

img_x = cv2.imread(path_name_x)

except IndexError:

print(path_name_x)

print('error')

else:

img_x_rgb = cv2.cvtColor(img_x, cv2.COLOR_BGR2RGB) # 转为RGB图片

face_align_rgb_x = detector.align(size, img_x_rgb)

if face_align_rgb_x is None:

det = dlib.get_frontal_face_detector()

gray_img = cv2.cvtColor(img_x, cv2.COLOR_BGR2GRAY)

# 使用detector进行人脸检测

dets = det(gray_img, 1)

if len(dets) > 0:

x1 = dets[0].top() if dets[0].top() > 0 else 0

y1 = dets[0].bottom() if dets[0].bottom() > 0 else 0

x2 = dets[0].left() if dets[0].left() > 0 else 0

y2 = dets[0].right() if dets[0].right() > 0 else 0

face = img_x[x1:y1, x2:y2]

else:

face = cv2.resize(img_x, (size, size))

face_align_x = cv2.resize(face, (size, size))

else:

face_align_x = cv2.cvtColor(face_align_rgb_x, cv2.COLOR_RGB2BGR) # 转为BGR图片

x_img = np.array(face_align_x)

x_img = x_img.astype('float32') / 255.0

return x_img

开发者ID:yeziyang1992,项目名称:Python-Tensorflow-Face-v2.0,代码行数:31,

注:本文中的cv2.COLOR_RGB2BGR属性示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。

python rgb bgr_Python cv2.COLOR_RGB2BGR属性代码示例相关推荐

  1. python画画bup_Python Tkinter.X属性代码示例

    本文整理汇总了Python中Tkinter.X属性的典型用法代码示例.如果您正苦于以下问题:Python Tkinter.X属性的具体用法?Python Tkinter.X怎么用?Python Tki ...

  2. python中plus_Python token.PLUS属性代码示例

    # 需要导入模块: import token [as 别名] # 或者: from token import PLUS [as 别名] def test_exact_type(self): self. ...

  3. python居中对齐代码end_Python tkinter.END属性代码示例

    本文整理汇总了Python中tkinter.END属性的典型用法代码示例.如果您正苦于以下问题:Python tkinter.END属性的具体用法?Python tkinter.END怎么用?Pyth ...

  4. python中type(12.34)_Python typing.TYPE_CHECKING属性代码示例

    本文整理汇总了Python中typing.TYPE_CHECKING属性的典型用法代码示例.如果您正苦于以下问题:Python typing.TYPE_CHECKING属性的具体用法?Python t ...

  5. python modifysetup什么意思_Python pyinotify.IN_MODIFY属性代码示例

    本文整理汇总了Python中pyinotify.IN_MODIFY属性的典型用法代码示例.如果您正苦于以下问题:Python pyinotify.IN_MODIFY属性的具体用法?Python pyi ...

  6. python space_Python locals.K_SPACE属性代码示例

    本文整理汇总了Python中pygame.locals.K_SPACE属性的典型用法代码示例.如果您正苦于以下问题:Python locals.K_SPACE属性的具体用法?Python locals ...

  7. python win32console_Python win32console.FOREGROUND_RED属性代码示例

    本文整理汇总了Python中win32console.FOREGROUND_RED属性的典型用法代码示例.如果您正苦于以下问题:Python win32console.FOREGROUND_RED属性 ...

  8. python trunc_Python os.O_TRUNC属性代码示例

    本文整理汇总了Python中os.O_TRUNC属性的典型用法代码示例.如果您正苦于以下问题:Python os.O_TRUNC属性的具体用法?Python os.O_TRUNC怎么用?Python ...

  9. python tkinter insert函数_Python tkinter.INSERT属性代码示例

    本文整理汇总了Python中tkinter.INSERT属性的典型用法代码示例.如果您正苦于以下问题:Python tkinter.INSERT属性的具体用法?Python tkinter.INSER ...

最新文章

  1. 【耗子啃过的SEO之入门知识二】SEOer必看,初级、中级和高级SEOer
  2. 上位机多个下位机modbustcp通讯_【C#上位机】西门子1200PLC实用定位控制程序案例...
  3. [css] 浏览器是怎样判断元素是否和某个CSS选择器匹配?
  4. python time模块
  5. DevOps vs Agile:有什么区别?
  6. python连接数据库设置编码_python操作mysql中文显示乱码的解决方法
  7. iOS 中关于 skip install
  8. dnp服务器未响应,PTP时间戳精度
  9. SAXParseException An invalid XML character 问题的解决
  10. cloud2声卡_带你解惑HyperX Cloud2(飓风)和Alpha(阿尔法)的终极选择
  11. 中国天气网 城市代号
  12. 移动互联网创业组织可持续发展模型
  13. 云原生架构下的 API 网关实践:Kong (三)
  14. 京东商品列表API接口-(item_search-按关键字搜索京东商品API接口),京东API接口
  15. 创建anaconda虚拟环境步骤
  16. python有趣小程序-搞几款由quot;Python”语言编写的quot;有趣、恶搞、好玩”的程序代码!...
  17. 对web移动端开发的一些了解
  18. github push不上去了 IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
  19. MBT-模型驱动测试的探索与实践(一)
  20. 程序内存空间(代码段、数据段、堆栈段)

热门文章

  1. 博拉博客营销——To Be Or Not To Be?
  2. mac安装Android SDK(使用idea)与Android SDK环境变量配置
  3. HBase原理深入解析(一)----HBase架构总览
  4. 深度解析leaf分布式id生成服务源码(号段模式)
  5. 如何快速接手做到一半的项目?
  6. iOS马甲包上架总结
  7. idea 错误提示乱提示 提示不及时
  8. AP5179 高端电流采样降压恒流驱动IC SOP8 LED车灯电源驱动
  9. 论文阅读:X-ray2Shape: Reconstruction of 3D Liver Shape from a Single 2D Projection Image
  10. Jquery控制全选反选