Python PIL.Image.merge() Examples
The following are 30
code examples of PIL.Image.merge().
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
PIL.Image
, or try the search function
.

Example #1
Source File: super_resolution.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 6 votes |
def resolve(ctx): from PIL import Image if isinstance(ctx, list): ctx = [ctx[0]] net.load_parameters('superres.params', ctx=ctx) img = Image.open(opt.resolve_img).convert('YCbCr') y, cb, cr = img.split() data = mx.nd.expand_dims(mx.nd.expand_dims(mx.nd.array(y), axis=0), axis=0) out_img_y = mx.nd.reshape(net(data), shape=(-3, -2)).asnumpy() out_img_y = out_img_y.clip(0, 255) out_img_y = Image.fromarray(np.uint8(out_img_y[0]), mode='L') out_img_cb = cb.resize(out_img_y.size, Image.BICUBIC) out_img_cr = cr.resize(out_img_y.size, Image.BICUBIC) out_img = Image.merge('YCbCr', [out_img_y, out_img_cb, out_img_cr]).convert('RGB') out_img.save('resolved.png')
Example #2
Source File: utils.py From emotion_classification with MIT License | 6 votes |
def distort_image(im, hue, sat, val): im = im.convert('HSV') cs = list(im.split()) cs[1] = cs[1].point(lambda i: i * sat) cs[2] = cs[2].point(lambda i: i * val) def change_hue(x): x += hue*255 if x > 255: x -= 255 if x < 0: x += 255 return x cs[0] = cs[0].point(change_hue) im = Image.merge(im.mode, tuple(cs)) im = im.convert('RGB') return im
Example #3
Source File: utils.py From emotion_classification with MIT License | 6 votes |
def distort_image(im, hue, sat, val): im = im.convert('HSV') cs = list(im.split()) cs[1] = cs[1].point(lambda i: i * sat) cs[2] = cs[2].point(lambda i: i * val) def change_hue(x): x += hue*255 if x > 255: x -= 255 if x < 0: x += 255 return x cs[0] = cs[0].point(change_hue) im = Image.merge(im.mode, tuple(cs)) im = im.convert('RGB') return im
Example #4
Source File: image.py From pytorch-0.4-yolov3 with MIT License | 6 votes |
def distort_image(im, hue, sat, val): im = im.convert('HSV') cs = list(im.split()) cs[1] = cs[1].point(lambda i: i * sat) cs[2] = cs[2].point(lambda i: i * val) def change_hue(x): x += hue*255 if x > 255: x -= 255 if x < 0: x += 255 return x cs[0] = cs[0].point(change_hue) im = Image.merge(im.mode, tuple(cs)) im = im.convert('RGB') #constrain_image(im) return im
Example #5
Source File: key.py From kle_render with MIT License | 6 votes |
def open_base_img(full_profile, res, base_color, color): # get base image according to profile and perceptual gray of key color base_num = str([0xE0, 0xB0, 0x80, 0x50, 0x20].index(base_color) + 1) # open image and convert to Lab with Image.open('images/{0}_{1}{2}.png'.format(*full_profile, base_num)) as img: key_img = img.resize((int(s * res / 200) for s in img.size), resample=Image.BILINEAR).convert('RGBA') if full_profile[1] in ('ISO', 'BIGENTER'): alpha = key_img.split()[-1] l, a, b = ImageCms.applyTransform(key_img, rgb2lab_transform).split() # convert key color to Lab # a and b should be scaled by 128/100, but desaturation looks more natural rgb_color = color_objects.sRGBColor(*ImageColor.getrgb(color), is_upscaled=True) lab_color = color_conversions.convert_color(rgb_color, color_objects.LabColor) l1, a1, b1 = lab_color.get_value_tuple() l1, a1, b1 = int(l1 * 256 / 100), int(a1 + 128), int(b1 + 128) # change Lab of base image to match that of key color l = ImageMath.eval('convert(l + l1 - l_avg, "L")', l=l, l1=l1, l_avg=base_color) a = ImageMath.eval('convert(a + a1 - a, "L")', a=a, a1=a1) b = ImageMath.eval('convert(b + b1 - b, "L")', b=b, b1=b1) key_img = ImageCms.applyTransform(Image.merge('LAB', (l, a, b)), lab2rgb_transform).convert('RGBA') if full_profile[1] in ('ISO', 'BIGENTER'): key_img.putalpha(alpha) return key_img
Example #6
Source File: loader.py From 3D-ResNets-PyTorch with MIT License | 6 votes |
def __call__(self, video_path, frame_indices): with h5py.File(video_path, 'r') as f: flow_data = [] for flow in self.flows: flow_data.append(f[f'video_{flow}']) video = [] for i in frame_indices: if i < len(flow_data[0]): frame = [ Image.open(io.BytesIO(video_data[i])) for video_data in flow_data ] frame.append(frame[-1]) # add dummy data into third channel video.append(Image.merge('RGB', frame)) return video
Example #7
Source File: super_resolution.py From training_results_v0.6 with Apache License 2.0 | 6 votes |
def resolve(ctx): from PIL import Image if isinstance(ctx, list): ctx = [ctx[0]] net.load_parameters('superres.params', ctx=ctx) img = Image.open(opt.resolve_img).convert('YCbCr') y, cb, cr = img.split() data = mx.nd.expand_dims(mx.nd.expand_dims(mx.nd.array(y), axis=0), axis=0) out_img_y = mx.nd.reshape(net(data), shape=(-3, -2)).asnumpy() out_img_y = out_img_y.clip(0, 255) out_img_y = Image.fromarray(np.uint8(out_img_y[0]), mode='L') out_img_cb = cb.resize(out_img_y.size, Image.BICUBIC) out_img_cr = cr.resize(out_img_y.size, Image.BICUBIC) out_img = Image.merge('YCbCr', [out_img_y, out_img_cb, out_img_cr]).convert('RGB') out_img.save('resolved.png')
Example #8
Source File: test_image_filter.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_consistency_5x5(self): source = Image.open("Tests/images/hopper.bmp") reference = Image.open("Tests/images/hopper_emboss_more.bmp") kernel = ImageFilter.Kernel((5, 5), # noqa: E127 (-1, -1, -1, -1, 0, -1, -1, -1, 0, 1, -1, -1, 0, 1, 1, -1, 0, 1, 1, 1, 0, 1, 1, 1, 1), 0.3) source = source.split() * 2 reference = reference.split() * 2 for mode in ['L', 'LA', 'RGB', 'CMYK']: self.assert_image_equal( Image.merge(mode, source[:len(mode)]).filter(kernel), Image.merge(mode, reference[:len(mode)]), )
Example #9
Source File: test_color_lut.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_channels_order(self): g = Image.linear_gradient('L') im = Image.merge('RGB', [g, g.transpose(Image.ROTATE_90), g.transpose(Image.ROTATE_180)]) # Reverse channels by splitting and using table self.assert_image_equal( Image.merge('RGB', im.split()[::-1]), im._new(im.im.color_lut_3d('RGB', Image.LINEAR, 3, 2, 2, 2, [ 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, ])))
Example #10
Source File: test_format_hsv.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 6 votes |
def wedge(self): w = Image._wedge() w90 = w.rotate(90) (px, h) = w.size r = Image.new('L', (px*3, h)) g = r.copy() b = r.copy() r.paste(w, (0, 0)) r.paste(w90, (px, 0)) g.paste(w90, (0, 0)) g.paste(w, (2*px, 0)) b.paste(w, (px, 0)) b.paste(w90, (2*px, 0)) img = Image.merge('RGB', (r, g, b)) return img
Example #11
Source File: deepfry.py From FlameCogs with MIT License | 6 votes |
def _fry(img): e = ImageEnhance.Sharpness(img) img = e.enhance(100) e = ImageEnhance.Contrast(img) img = e.enhance(100) e = ImageEnhance.Brightness(img) img = e.enhance(.27) r, b, g = img.split() e = ImageEnhance.Brightness(r) r = e.enhance(4) e = ImageEnhance.Brightness(g) g = e.enhance(1.75) e = ImageEnhance.Brightness(b) b = e.enhance(.6) img = Image.merge('RGB', (r, g, b)) e = ImageEnhance.Brightness(img) img = e.enhance(1.5) temp = BytesIO() temp.name = 'deepfried.png' img.save(temp) temp.seek(0) return temp
Example #12
Source File: sensor.py From coiltraine with MIT License | 6 votes |
def save_to_disk(self, filename, format='.png'): """Save this image to disk (requires PIL installed).""" filename = _append_extension(filename, format) try: from PIL import Image as PImage except ImportError: raise RuntimeError( 'cannot import PIL, make sure pillow package is installed') image = PImage.frombytes( mode='RGBA', size=(self.width, self.height), data=self.raw_data, decoder_name='raw') color = image.split() image = PImage.merge("RGB", color[2::-1]) folder = os.path.dirname(filename) if not os.path.isdir(folder): os.makedirs(folder) image.save(filename, quality=100)
Example #13
Source File: inference_with_net.py From TableTrainNet with MIT License | 6 votes |
def from_png_to_bmp(png_path, output_path=BMP_IMAGE_TEST_TO_PATH): """ Convert a png_path image into a bmp 3-channel one and return the path to the converted image :param png_path: path of the image :param output_path: path in which we save the image :return: the file path """ # convert a .png image file to a .bmp image file using PIL file_name = os.path.splitext(png_path)[0] \ .split("/")[-1] file_in = png_path img = Image.open(file_in) file_out = os.path.join(output_path, str(file_name), str(file_name) + '.bmp') len(img.split()) # test if len(img.split()) == 4: # prevent IOError: cannot write mode RGBA as BMP r, g, b, a = img.split() img = Image.merge("RGB", (r, g, b)) img.save(file_out) else: img.save(file_out) return file_out
Example #14
Source File: sensor.py From Hands-On-Intelligent-Agents-with-OpenAI-Gym with MIT License | 6 votes |
def save_to_disk(self, filename): """Save this image to disk (requires PIL installed).""" filename = _append_extension(filename, '.png') try: from PIL import Image as PImage except ImportError: raise RuntimeError( 'cannot import PIL, make sure pillow package is installed') image = PImage.frombytes( mode='RGBA', size=(self.width, self.height), data=self.raw_data, decoder_name='raw') color = image.split() image = PImage.merge("RGB", color[2::-1]) folder = os.path.dirname(filename) if not os.path.isdir(folder): os.makedirs(folder) image.save(filename)
Example #15
Source File: sensor.py From Hands-On-Intelligent-Agents-with-OpenAI-Gym with MIT License | 6 votes |
def save_to_disk(self, filename): """Save this image to disk (requires PIL installed).""" filename = _append_extension(filename, '.png') try: from PIL import Image as PImage except ImportError: raise RuntimeError( 'cannot import PIL, make sure pillow package is installed') image = PImage.frombytes( mode='RGBA', size=(self.width, self.height), data=self.raw_data, decoder_name='raw') color = image.split() image = PImage.merge("RGB", color[2::-1]) folder = os.path.dirname(filename) if not os.path.isdir(folder): os.makedirs(folder) image.save(filename)
Example #16
Source File: utils.py From YOLO with MIT License | 6 votes |
def distort_image(im, hue, sat, val): im = im.convert('HSV') cs = list(im.split()) cs[1] = cs[1].point(lambda i: i * sat) cs[2] = cs[2].point(lambda i: i * val) def change_hue(x): x += hue*255 if x > 255: x -= 255 if x < 0: x += 255 return x cs[0] = cs[0].point(change_hue) im = Image.merge(im.mode, tuple(cs)) im = im.convert('RGB') return im # generate random scale.
Example #17
Source File: super_resolution.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 5 votes |
def perform_inference(sym, arg_params, aux_params, input_img, img_cb, img_cr): """Perform inference on image using mxnet""" metadata = onnx_mxnet.get_model_metadata('super_resolution.onnx') data_names = [input_name[0] for input_name in metadata.get('input_tensor_data')] # create module mod = mx.mod.Module(symbol=sym, data_names=data_names, label_names=None) mod.bind(for_training=False, data_shapes=[(data_names[0], input_img.shape)]) mod.set_params(arg_params=arg_params, aux_params=aux_params) # run inference batch = namedtuple('Batch', ['data']) mod.forward(batch([mx.nd.array(input_img)])) # Save the result img_out_y = Image.fromarray(np.uint8(mod.get_outputs()[0][0][0]. asnumpy().clip(0, 255)), mode='L') result_img = Image.merge( "YCbCr", [img_out_y, img_cb.resize(img_out_y.size, Image.BICUBIC), img_cr.resize(img_out_y.size, Image.BICUBIC)]).convert("RGB") output_img_dim = 672 assert result_img.size == (output_img_dim, output_img_dim) LOGGER.info("Super Resolution example success.") result_img.save("super_res_output.jpg") return result_img
Example #18
Source File: playertoken.py From avrae with GNU General Public License v3.0 | 5 votes |
def color(src, target): num_pixels = src.size[0] * src.size[1] colors = src.getcolors(num_pixels) rgb = sum(c[0] * c[1][0] for c in colors), sum(c[0] * c[1][1] for c in colors), sum( c[0] * c[1][2] for c in colors) rgb = rgb[0] / num_pixels, rgb[1] / num_pixels, rgb[2] / num_pixels bands = target.split() for i, v in enumerate(rgb): out = bands[i].point(lambda p: int(p * v / 255)) bands[i].paste(out) return Image.merge(target.mode, bands)
Example #19
Source File: image.py From pytorch-0.4-yolov3 with MIT License | 5 votes |
def scale_image_channel(im, c, v): cs = list(im.split()) cs[c] = cs[c].point(lambda i: i * v) out = Image.merge(im.mode, tuple(cs)) return out
Example #20
Source File: pil_utils.py From FastMaskRCNN with Apache License 2.0 | 5 votes |
def draw_bbox(step, image, name='', image_height=1, image_width=1, bbox=None, label=None, gt_label=None, prob=None): #print(prob[:,label]) source_img = Image.fromarray(image) b, g, r = source_img.split() source_img = Image.merge("RGB", (r, g, b)) draw = ImageDraw.Draw(source_img) color = '#0000ff' if bbox is not None: for i, box in enumerate(bbox): if label is not None: if prob is not None: if (prob[i,label[i]] > 0.5) and (label[i] > 0): if gt_label is not None: text = cat_id_to_cls_name(label[i]) + ' : ' + cat_id_to_cls_name(gt_label[i]) if label[i] != gt_label[i]: color = '#ff0000'#draw.text((2+bbox[i,0], 2+bbox[i,1]), cat_id_to_cls_name(label[i]) + ' : ' + cat_id_to_cls_name(gt_label[i]), fill='#ff0000') else: color = '#0000ff' else: text = cat_id_to_cls_name(label[i]) draw.text((2+bbox[i,0], 2+bbox[i,1]), text, fill=color) if _DEBUG is True: print("plot",label[i], prob[i,label[i]]) draw.rectangle(box,fill=None,outline=color) else: if _DEBUG is True: print("skip",label[i], prob[i,label[i]]) else: text = cat_id_to_cls_name(label[i]) draw.text((2+bbox[i,0], 2+bbox[i,1]), text, fill=color) draw.rectangle(box,fill=None,outline=color) return source_img.save(FLAGS.train_dir + '/est_imgs/test_' + name + '_' + str(step) +'.jpg', 'JPEG')
Example #21
Source File: neural_style.py From neural-style-pt with MIT License | 5 votes |
def original_colors(content, generated): content_channels = list(content.convert('YCbCr').split()) generated_channels = list(generated.convert('YCbCr').split()) content_channels[0] = generated_channels[0] return Image.merge('YCbCr', content_channels).convert('RGB') # Print like Lua/Torch7
Example #22
Source File: multi_gpu.py From MoePhoto with Apache License 2.0 | 5 votes |
def multi_gpu_run(model, im_path, outpath, gpus): print('running with multi GPU') # 如果patch一样大,开这个会加速 cudnn.benchmark = True # 输入2D Tensor=[Batch,Channel,H,W] dataset = DatasetFromImage(im_path) # 暂定一个GPU跑一张图 loader = DataLoader(dataset=dataset, batch_size=gpus) trans = transforms.Compose([ transforms.ToPILImage(), ]) for iter, batch in enumerate(loader, 1): y = batch[0] bicubic = batch[1] names = batch[2] # print(y) if torch.cuda.is_available(): y = y.cuda() else: y = y.cpu() im_h_y = model(y) print(im_h_y.shape) #得看下shape,此处应该有个循环,把batch分解成多个图再合成 im_h_y = trans(im_h_y) bicubic = trans(bicubic).convert("YCbCr") y, cb, cr = bicubic.split() HR = Image.merge('YCbCr', (im_h_y, cb, cr)) HR.save(outpath)
Example #23
Source File: mpv.py From python-mpv with GNU Affero General Public License v3.0 | 5 votes |
def screenshot_raw(self, includes='subtitles'): """Mapped mpv screenshot_raw command, see man mpv(1). Returns a pillow Image object.""" from PIL import Image res = self.node_command('screenshot-raw', includes) if res['format'] != 'bgr0': raise ValueError('Screenshot in unknown format "{}". Currently, only bgr0 is supported.' .format(res['format'])) img = Image.frombytes('RGBA', (res['stride']//4, res['h']), res['data']) b,g,r,a = img.split() return Image.merge('RGB', (r,g,b))
Example #24
Source File: coco_loader.py From sunets with MIT License | 5 votes |
def r_rotate(self, img, lbl): angle = random.uniform(-10, 10) lbl = np.array(lbl, dtype=np.int32) - self.ignore_index lbl = Image.fromarray(lbl) img = tuple([ImageMath.eval("int(a)-b", a=j, b=self.filler[i]) for i, j in enumerate(img.split())]) lbl = lbl.rotate(angle, resample=Image.NEAREST) img = tuple([k.rotate(angle, resample=Image.BICUBIC) for k in img]) lbl = ImageMath.eval("int(a)+b", a=lbl, b=self.ignore_index) img = Image.merge(mode='RGB', bands=tuple( [ImageMath.eval("convert(int(a)+b,'L')", a=j, b=self.filler[i]) for i, j in enumerate(img)])) return (img, lbl)
Example #25
Source File: pascal_voc_loader.py From sunets with MIT License | 5 votes |
def r_rotate(self, img, lbl): angle = random.uniform(-10, 10) lbl = np.array(lbl, dtype=np.int32) - self.ignore_index lbl = Image.fromarray(lbl) img = tuple([ImageMath.eval("int(a)-b", a=j, b=self.filler[i]) for i, j in enumerate(img.split())]) lbl = lbl.rotate(angle, resample=Image.NEAREST) img = tuple([k.rotate(angle, resample=Image.BICUBIC) for k in img]) lbl = ImageMath.eval("int(a)+b", a=lbl, b=self.ignore_index) img = Image.merge(mode='RGB', bands=tuple( [ImageMath.eval("convert(int(a)+b,'L')", a=j, b=self.filler[i]) for i, j in enumerate(img)])) return (img, lbl)
Example #26
Source File: mpv_bak.py From kawaii-player with GNU General Public License v3.0 | 5 votes |
def screenshot_raw(self, includes='subtitles'): """Mapped mpv screenshot_raw command, see man mpv(1). Returns a pillow Image object.""" from PIL import Image res = self.node_command('screenshot-raw', includes) if res['format'] != 'bgr0': raise ValueError('Screenshot in unknown format "{}". Currently, only bgr0 is supported.' .format(res['format'])) img = Image.frombytes('RGBA', (res['w'], res['h']), res['data']) b,g,r,a = img.split() return Image.merge('RGB', (r,g,b))
Example #27
Source File: test_image_filter.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_consistency_3x3(self): source = Image.open("Tests/images/hopper.bmp") reference = Image.open("Tests/images/hopper_emboss.bmp") kernel = ImageFilter.Kernel((3, 3), # noqa: E127 (-1, -1, 0, -1, 0, 1, 0, 1, 1), .3) source = source.split() * 2 reference = reference.split() * 2 for mode in ['L', 'LA', 'RGB', 'CMYK']: self.assert_image_equal( Image.merge(mode, source[:len(mode)]).filter(kernel), Image.merge(mode, reference[:len(mode)]), )
Example #28
Source File: test_box_blur.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 5 votes |
def assertBlur(self, im, radius, data, passes=1, delta=0): # check grayscale image self.assertImage(self.box_blur(im, radius, passes), data, delta) rgba = Image.merge('RGBA', (im, im, im, im)) for band in self.box_blur(rgba, radius, passes).split(): self.assertImage(band, data, delta)
Example #29
Source File: test_file_mic.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_sanity(self): im = Image.open(TEST_FILE) im.load() self.assertEqual(im.mode, "RGBA") self.assertEqual(im.size, (128, 128)) self.assertEqual(im.format, "MIC") # Adjust for the gamma of 2.2 encoded into the file lut = ImagePalette.make_gamma_lut(1/2.2) im = Image.merge('RGBA', [chan.point(lut) for chan in im.split()]) im2 = hopper("RGBA") self.assert_image_similar(im, im2, 10)
Example #30
Source File: test_color_lut.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_identities_4_channels(self): g = Image.linear_gradient('L') im = Image.merge('RGB', [g, g.transpose(Image.ROTATE_90), g.transpose(Image.ROTATE_180)]) # Red channel copied to alpha self.assert_image_equal( Image.merge('RGBA', (im.split()*2)[:4]), im._new(im.im.color_lut_3d('RGBA', Image.LINEAR, *self.generate_identity_table(4, 17))))