def _merge_bands(bands, color_mode, size, icc_profile): if Image is None: raise Exception("This module requires PIL (or Pillow) installed.") if color_mode == ColorMode.RGB: merged_image = Image.merge('RGB', [bands[key] for key in 'RGB']) elif color_mode == ColorMode.CMYK: merged_image = Image.merge('CMYK', [bands[key] for key in 'CMYK']) merged_bytes = tobytes(merged_image) # colors are inverted in Photoshop CMYK images; invert them back merged_image = frombytes('CMYK', size, merged_bytes, 'raw', 'CMYK;I') elif color_mode == ColorMode.GRAYSCALE: merged_image = bands['L'] else: raise NotImplementedError() if icc_profile is not None: assert ImageCms is not None try: if color_mode in [ColorMode.RGB, ColorMode.CMYK]: merged_image = ImageCms.profileToProfile(merged_image, icc_profile, icc_profiles.sRGB, outputMode='RGB') elif color_mode == ColorMode.GRAYSCALE: ImageCms.profileToProfile(merged_image, icc_profile, icc_profiles.gray, inPlace=True, outputMode='L') except ImageCms.PyCMSError as e: # PIL/Pillow/(old littlecms?) can't convert some ICC profiles warnings.warn(repr(e)) if color_mode == ColorMode.CMYK: merged_image = merged_image.convert('RGB') alpha = bands.get('A') if alpha: merged_image.putalpha(alpha) return merged_image
def Make_Image_Black_and_White(self,imagePath,savePath): """ Takes an images and makes black and white. :param imagePath: Saved image path :type imagePath: String :param savePath: Save to path :type savePath: String :return: Save location :rtype: String """ self.tempFiles += [ imagePath,savePath ] try: im = Image.open( imagePath ) i = im.split() Image.merge("RGB", (i[1],i[1],i[1])).save( savePath ) self.Pause_Until_File_Exists( savePath ) return savePath except (ValueError, IndexError): return imagePath
def parse_image_data(self): if not self.header: self.parse_header() if not self.ressources: self._skip_block("image resources", new_line=True) self.ressources = "not parsed" if not self.layers: self._skip_block("image layers", new_line=True) self.layers = "not parsed" self.merged_image = [] li = {} li["chids"] = range(self.header["channels"]) li["chlengths"] = [None] * self.header["channels"] # dummy data (li["name"], li["channels"], li["rows"], li["cols"]) = ( "merged", self.header["channels"], self.header["rows"], self.header["cols"], ) li["layernum"] = -1 self.parse_image(li, is_layer=False) if li["channels"] == 1: self.merged_image = self.merged_image[0] elif li["channels"] == 3: self.merged_image = Image.merge("RGB", self.merged_image) elif li["channels"] >= 4 and self.header["mode"] == 3: self.merged_image = Image.merge("RGBA", self.merged_image[:4]) else: raise ValueError("Unsupported mode or number of channels")
def wximage_to_pil(wximage): # print 'wximage_to_pil', wximage size = (wximage.Width, wximage.Height) img = Image.new('RGB', size) img.fromstring(wximage.Data) r, g, b = img.split() if wximage.HasAlpha() or wximage.HasMask(): a = Image.new('L', wximage.GetSize()) # images that come from formats like GIF don't have an alpha channel # but DO have a mask color set if wximage.HasMask(): if not wximage.HasAlpha(): # uses that mask color to generate an alpha channel. wximage.InitAlpha() if wximage.HasAlpha(): a.fromstring(wximage.AlphaData) img = Image.merge('RGBA', (r, g, b, a)) else: img = Image.merge('RGB', (r, g, b)) return img
def equalize_hist_average(input_img): ''' apply the average histogram equalization to process the R, G, B channels individually ''' source = input_img.split() out = [None, None, None] p = [] for i in range(3): p.append(plot_hist(source[i], '')) result = average_hist(p) reflect = [0] * 256 curSum = 0 for i in range(256): curSum += result[i] reflect[i] = 255 * curSum #print i, " ", reflect[i] for i in range(3): out[i] = Image.new('L', input_img.size) for h in range(input_img.size[1]): for w in range(input_img.size[0]): pixel = source[i].getpixel((w, h)) out[i].putpixel((w, h), reflect[pixel]) if len(source) == 3: output_img = Image.merge('RGB', tuple(out)) else: out.append(source[3]) output_img = Image.merge('RGBA', tuple(out)) return output_img
def convert_image(self, img, alpha=True): ''' converts image from RGB to RGBA or RGB to RGB @param img: Image.Image object @param alpha: boolean (default=True) @return Image.Image object or False on error ''' self.log.debug('Image convertor start, params: %s, alpha=%s' % (img, alpha)) try: if img.mode == 'RGB': # image doesn't have alpha return img else: if alpha: # not changing, img = img r, g, b, a = img.split() img = Image.merge('RGBA', (r, g, b, a)) else: r, g, b, a = img.split() img = Image.merge('RGB', (r, g, b)) return img except AttributeError as e: self.log.debug('Not converting from RGBA to RGB, error: %s' % (e)) self.log.exception('Exception on image convertor') self.log.error('cannot convert image, check if image is in correct dir, converted_image = %s' % (img)) print 'Image conversion error, check log for details. Exiting' sys.exit(1)
def paste_with_alpha(bg, img, offset): """Same as image.paste, but correctly works when source has gamma too""" r, g, b, a = img.split() transformed_rgb = Image.merge("RGB", (r, g, b)) transformed_mask = Image.merge("L", (a,)) bg.paste(transformed_rgb, offset, transformed_mask) return bg
def execute(self, image, query): athor = get_image_object(self.image, self.storage) x2, y2 = athor.size x1 = get_coords(image.size[0], athor.size[0], self.x) y1 = get_coords(image.size[1], athor.size[1], self.y) box = ( x1, y1, x1 + x2, y1 + y2, ) # Note that if you paste an "RGBA" image, the alpha band is ignored. # You can work around this by using the same image as both source image and mask. image = image.copy() if athor.mode == 'RGBA': if image.mode == 'RGBA': channels = image.split() alpha = channels[3] image = Image.merge('RGB', channels[0:3]) athor_channels = athor.split() athor_alpha = athor_channels[3] athor = Image.merge('RGB', athor_channels[0:3]) image.paste(athor, box, mask=athor_alpha) # merge alpha athor_image_alpha = Image.new('L', image.size, color=0) athor_image_alpha.paste(athor_alpha, box) new_alpha = ImageChops.add(alpha, athor_image_alpha) image = Image.merge('RGBA', image.split() + (new_alpha,)) else: image.paste(athor, box, mask=athor) else: image.paste(athor, box) return image
def parse_image_data(self): if not self.header: self.parse_header() if not self.ressources: self._skip_block("image resources", new_line=True) self.ressources = 'not parsed' if not self.layers: self._skip_block("image layers", new_line=True) self.layers = 'not parsed' self.merged_image = [] li = {} li['chids'] = range(self.header['channels']) li['chlengths'] = [ None ] * self.header['channels'] # dummy data (li['name'], li['channels'], li['rows'], li['cols']) = ('merged', self.header['channels'], self.header['rows'], self.header['cols']) li['layernum'] = -1 self.parse_image(li, is_layer=False) if li['channels'] == 1: self.merged_image = self.merged_image[0] elif li['channels'] == 3: self.merged_image = Image.merge('RGB', self.merged_image) elif li['channels'] >= 4 and self.header['mode'] == 3: self.merged_image = Image.merge('RGBA', self.merged_image[:4]) else: raise ValueError('Unsupported mode or number of channels')
def generate_wm_modes(dst_path, prefix): band_1 = Image.new('1', (16, 16)) band_1.putdata([0] * 128 + [1] * 128) band_8 = Image.new('L', (16, 16)) band_8.putdata(range(256)) band_a = Image.new('L', (16, 16)) band_a.putdata([255]*256) wm_1 = Image.merge('1', [band_1]) wm_1.save(os.path.join(dst_path, 'gen-{0}-wm-1.png'.format(prefix))) wm_l = Image.merge('L', [band_8]) wm_l.save(os.path.join(dst_path, 'gen-{0}-wm-l.png'.format(prefix))) wm_rgb = Image.merge('RGB', [band_8, band_8, band_8]) wm_rgb.save(os.path.join(dst_path, 'gen-{0}-wm-rgb.png'.format(prefix))) wm_rgba = Image.merge('RGBA', [band_8, band_8, band_8, band_a]) wm_rgba.save(os.path.join(dst_path, 'gen-{0}-wm-rgba.png'.format(prefix))) #wm_cmyk = Image.merge('CMYK', [band_8, band_8, band_8, band_8]) #wm_cmyk.save(os.path.join(dst_path, 'gen-{0}-wm-cmyk.jpg'.format(prefix))) band_img = Image.new('L', (16, 16)) band_img.putdata([255]*64 + [0]*64 + [255]*64 + [0]*64) img = Image.merge('L', [band_img]) img.save(os.path.join(dst_path, 'gen-{0}-img.png'.format(prefix)))
def array_to_image(arr, alpha=None): """Convert a numpy array to grayscale or RGB(A) image. The numpy array `arr` can either have the shape (w, h) for a grayscale image result or a (3, w, h) shape for an RGB image. The alpha channel data in `alpha` will be applied to the resulting RGB image if supplied. `arr` is expected to have values in the range of 0.0..1.0. """ def make_image(arr): """Convert numpy array to image.""" return Image.fromarray((arr * 255).astype("uint8")) # Produce an RGB(A) image from an array with three values per point. if arr.ndim == 3: ni = list(range(3)) for i in ni: ni[i] = make_image(arr[i]) if alpha: res = Image.merge("RGBA", ni + [alpha]) else: res = Image.merge("RGB", ni) # Produce a grayscale image from a 1-value array. elif arr.ndim == 2: res = make_image(arr) else: raise ValueError return res
def alpha_composite(output, image, pos, rotation): if rotation: size = image.size image = image.rotate(rotation, expand=1).resize(size, Image.ANTIALIAS) r, g, b, a = image.split() rgb = Image.merge("RGB", (r, g, b)) mask = Image.merge("L", (a,)) output.paste(rgb, pos, mask)
def composite(top, bottom, offset): bottom = bottom.copy() top = top.convert('RGBA') r, g, b, a = top.split() top = PILImage.merge("RGB", (r, g, b)) mask = PILImage.merge("L", (a,)) bottom.paste(top, tuple(offset), mask) return bottom
def render_results_as_image(raster_data_path, way_bitmap, training_labels, test_labels, band_list, tile_size, predictions=None): ''' save the source TIFF as a JPEG, with labels and data overlaid ''' timestr = time.strftime("%Y%m%d-%H%M%S") outfile = os.path.splitext(raster_data_path)[0] + '-' + timestr + ".jpeg" # TIF to JPEG bit from: from: # http://stackoverflow.com/questions/28870504/converting-tiff-to-jpeg-in-python im = Image.open(raster_data_path) print("GENERATING JPEG for %s" % raster_data_path) rows = len(way_bitmap) cols = len(way_bitmap[0]) t0 = time.time() r, g, b, ir = im.split() # visualize single band analysis tinted for R-G-B, # or grayscale for infrared band if sum(band_list) == 1: if band_list[3] == 1: # visualize IR as grayscale im = Image.merge("RGB", (ir, ir, ir)) else: # visualize single-color band analysis as a scale of that color zeros_band = Image.new('RGB', r.size).split()[0] if band_list[0] == 1: im = Image.merge("RGB", (r, zeros_band, zeros_band)) elif band_list[1] == 1: im = Image.merge("RGB", (zeros_band, g, zeros_band)) elif band_list[2] == 1: im = Image.merge("RGB", (zeros_band, zeros_band, b)) else: # visualize multi-band analysis as RGB im = Image.merge("RGB", (r, g, b)) t1 = time.time() print("{0:.1f}s to FLATTEN the {1} analyzed bands of TIF to JPEG".format(t1 - t0, sum( band_list))) t0 = time.time() shade_labels(im, test_labels, predictions, tile_size) t1 = time.time() print("{0:.1f}s to SHADE PREDICTIONS on JPEG".format(t1 - t0)) t0 = time.time() # show raw data that spawned the labels for row in range(0, rows): for col in range(0, cols): if way_bitmap[row][col] != 0: im.putpixel((col, row), (255, 0, 0)) t1 = time.time() print("{0:.1f}s to DRAW WAYS ON JPEG".format(t1 - t0)) im.save(outfile, "JPEG")
def read_channels_as_image(f, channels, width, height): oripos = f.tell() imgs = {} #for k in range(len(channels)): for channel in channels: # 沒影像的圖層, 可能是圖層資料夾 #if 'Compression' not in layer['Channels'][k]: # continue id = channel['Id'] compression = channel['Compression'] ptr = channel['PosInFile'] datalen = channel['Length'] f.seek(ptr, os.SEEK_SET) data = f.read(datalen) cdata = DecodeChannelImageData(data, compression, width, height) img = Image.frombuffer("L", (width, height), cdata, 'raw', "L", 0, 1) imgs[id] = img result = None if imgs: alpha = None if CHANNEL_ALPHA_1 in imgs: alpha = imgs[CHANNEL_ALPHA_1] if CHANNEL_ALPHA_2 in imgs: if alpha is None: alpha = imgs[CHANNEL_ALPHA_2] else: alpha.paste(255, None, imgs[CHANNEL_ALPHA_2]) if CHANNEL_ALPHA_3 in imgs: if alpha is None: alpha = imgs[CHANNEL_ALPHA_3] else: alpha.paste(255, None, imgs[CHANNEL_ALPHA_3]) if CHANNEL_RED in imgs and CHANNEL_GREEN in imgs and CHANNEL_BLUE in imgs: rgb = (imgs[CHANNEL_RED], imgs[CHANNEL_GREEN], imgs[CHANNEL_BLUE]) if alpha: result = Image.merge("RGBA", rgb + (alpha,)) else: result = Image.merge("RGB", rgb) elif CHANNEL_RED in imgs: # 還沒考慮多重色版的狀況 if alpha: result = Image.merge("LA", (imgs[CHANNEL_RED], alpha)) else: result = Image.merge("L", (imgs[CHANNEL_RED])) else: logging.error(imgs.keys()) raise f.seek(oripos, os.SEEK_SET) return result
def __init__(self, color, radius): width = height = radius * 2 + 1 splat = Image.new("RGBA", (width, height)) c = ImageDraw.ImageDraw(splat, "RGBA") (x, y) = (radius,) * 2 c.ellipse((x - radius, y - radius, x + radius, y + radius), fill=color) r, g, b, a = splat.split() self.splat = Image.merge("RGB", (r, g, b)) self.mask = Image.merge("L", (a,))
def invertimage(image): if image.mode == 'RGBA': r,g,b,a = image.split() rgb_image = Image.merge('RGB', (r,g,b)) inverted_image = ImageOps.invert(rgb_image) r2,g2,b2 = inverted_image.split() final_image = Image.merge('RGBA', (r2,g2,b2,a)) else: final_image = ImageOps.invert(image) return final_image
def invert(img): if img.mode == 'RGBA': r,g,b,a = img.split() rgb_image = Image.merge('RGB', (r,g,b)) aux = PIL.ImageOps.invert(rgb_image) r2,g2,b2 = aux.split() aux2 = Image.merge('RGBA', (r2,g2,b2,a)) else: aux2 = PIL.ImageOps.invert(image) return aux
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))))
def get_image(self): if occupant != None: bottom = self.image top = occupant.get_image r, g, b, a = top.split() top = Image.merge("RGB", (r, g, b)) mask = Image.merge("L", (a,)) bottom.paste(top, (0, 0), mask) return bottom else: return self.image
def inverse(inpng, outpng): image = Image.open(inpng) if image.mode == 'RGBA': r, g, b, a = image.split() rgb_image = Image.merge('RGB', (r, g, b)) inverted_image = PIL.ImageOps.invert(rgb_image) r2, g2, b2 = inverted_image.split() final_transparent_image = Image.merge('RGBA', (r2, g2, b2, a)) final_transparent_image.save(outpng) else: inverted_image = PIL.ImageOps.invert(image) inverted_image.save(outpng)
def generate_img_modes_types(dst_path, prefix): band_data = [255, 255, 255, 255, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 255, 255, 255, 255] band_wm = Image.new('L', (10, 5)) band_wm.putdata(band_data) for format_ in ('png', 'gif', 'bmp'): img = Image.merge('L', [band_wm]) img.save(os.path.join(dst_path, 'gen-{0}-g.{1}'.format(prefix, format_))) for format_ in ('png', 'bmp', 'jpg'): img = Image.merge('RGB', [band_wm]*3) img.save(os.path.join(dst_path, 'gen-{0}-rgb.{1}'.format(prefix, format_)))
def _alpha_composite(self, src, dst): """places a background in place of transparancy. We need this because we are converting to jpeg. peppered with gevent.sleep(0) to be a little less blocking. """ r, g, b, a = src.split() src = PilImage.merge("RGB", (r, g, b)) gevent.sleep(0) mask = PilImage.merge("L", (a,)) gevent.sleep(0) dst.paste(src, (0, 0), mask) gevent.sleep(0) return dst
def filter2d_rgb(input_img, filter_type, size): source = input_img.split() out = [None, None, None] for i in range(3): out[i] = filter2d(source[i], filter_type, size) if len(source) == 3: output_img = Image.merge('RGB', tuple(out)) else: out.append(source[3]) output_img = Image.merge('RGBA', tuple(out)) return output_img
def feed(self, buffer_O, buffer_L, buffer_R, step, l_cab, r_cab): """ feed 3 picture buffer and a step index note that this step index is the input p1[x-coordinate, y-coord, z-coord, r, g, b, step, x, y] """ img_O = self.to_image(buffer_O) img_L = self.to_image(buffer_L) img_R = self.to_image(buffer_R) path = "" if os.path.exists("C:\\DeltaScanResult"): path = "C:\\DeltaScanResult" if os.path.exists("DeltaScanResult"): path = "DeltaScanResult" if os.path.exists("/Users/simon/Dev/ScanResult"): path = "/Users/simon/Dev/ScanResult" # Check Domain if path != "": im1 = Image.fromarray(img_O) b, g, r = im1.split() im1 = Image.merge("RGB", (r, g, b)) im1.save("/Users/simon/Dev/ScanResult/%03d_O.png" % (step)) im2 = Image.fromarray(img_L) b, g, r = im2.split() im2 = Image.merge("RGB", (r, g, b)) im2.save("/Users/simon/Dev/ScanResult/%03d_L.png" % (step)) im3 = Image.fromarray(img_R) b, g, r = im3.split() im3 = Image.merge("RGB", (r, g, b)) im3.save("/Users/simon/Dev/ScanResult/%03d_R.png" % (step)) im = ImageChops.difference(im2, im1) im.save("/Users/simon/Dev/ScanResult/%03d_D.png" % (step)) indices_L = self.fs_L.subProcess(img_O, img_L, self.settings.img_height) indices_L = [[p[0], p[1] + l_cab]for p in indices_L] # indices_L = [[i, step] for i in range(self.settings.img_height)] point_L_this = self.fs_L.img_to_points(img_O, img_L, indices_L, step, 'L', l_cab, clock=True) self.points_L.extend(point_L_this) # return [self.points_to_bytes(point_L_this), []] indices_R = self.fs_R.subProcess(img_O, img_R, self.settings.img_height) indices_R = [[p[0], p[1] + r_cab]for p in indices_R] point_R_this = self.fs_R.img_to_points(img_O, img_R, indices_R, step, 'R', r_cab, clock=True) self.points_R.extend(point_R_this) # return [[], self.points_to_bytes(point_R_this)] return [self.points_to_bytes(point_L_this), self.points_to_bytes(point_R_this)]
def sepia(self, *args): level = 50 grayscale = self.buffer.convert('L') red = grayscale.point(lambda i: i + level*1.5) green = grayscale.point(lambda i: i + level) blue = grayscale.point(lambda i: i - level*0.5) bands = self.buffer.getbands() if 'A' not in bands: self.buffer = Image.merge('RGB', (red, green, blue)) else: source = self.buffer.split() alpha = source[bands.index('A')] self.buffer = Image.merge('RGBA', (red, green, blue, alpha)) self._load()
def f1(image, img): image = ImageEnhance.Brightness(image).enhance(1.1) bands = image.split() bands[R].paste(bands[R].point(lambda i: i + 2 ** ((255 - i) ** 0.25))) image = Image.merge(image.mode, bands) image = ImageEnhance.Contrast(image).enhance(1.15) bands = image.split() bands[G].paste(bands[G].point(lambda i: i * 0.9)) image = Image.merge(image.mode, bands) return image
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), (-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)]), )
def apply_image(map_img, input_img): ''' ''' h = map_img.size[1] # Check for a known height if h not in (2, 4, 6, 16, 18, 52, 86, 256): raise NotImplementedError('height: {0}'.format(map_img.size[1])) # denominator for later d = 0xff // (h - 1) # axes: input green, input red, input blue, output rgb cube = numpy.fromstring(map_img.tostring(), numpy.ubyte).reshape((h, h, h, 3)) # split input into RGB channel arrays input_img_ = input_img.convert('RGB') input_r, input_g, input_b = map(img2arr, input_img_.split()) # map input to output out_arr = cube[input_g/d, input_r/d, input_b/d] # merge output channel arrays to image out_rgb = out_arr[:,:,0], out_arr[:,:,1], out_arr[:,:,2] output_img = Image.merge('RGB', map(arr2img, out_rgb)) return output_img
def create_test_image(): # set up test image with something interesting in the tested aux # channel. nine_grid_deltas = [ (-1, -1), (-1, 0), (-1, 1), ( 0, -1), ( 0, 0), ( 0, 1), ( 1, -1), ( 1, 0), ( 1, 1), ] chans = [] bands = ImageMode.getmode(mode).bands for band_ndx in range(len(bands)): channel_type = 'L' # 8-bit unorm channel_pattern = hopper(channel_type) # paste pattern with varying offsets to avoid correlation # potentially hiding some bugs (like channels getting mixed). paste_offset = ( int(band_ndx / float(len(bands)) * channel_pattern.size[0]), int(band_ndx / float(len(bands) * 2) * channel_pattern.size[1]) ) channel_data = Image.new(channel_type, channel_pattern.size) for delta in nine_grid_deltas: channel_data.paste(channel_pattern, tuple(paste_offset[c] + delta[c]*channel_pattern.size[c] for c in range(2))) chans.append(channel_data) return Image.merge(mode, chans)
imGreyscale = img.convert('L') r, g, b, a = imAlpha.split() #split into r, g, b, a intensity images # LOGICAL COLOR OPERATIONS: # Intersection: imIntersect = ImageMath.eval("convert(a&b,'L')", a=r, b=b) # red and blue imIntersect2 = ImageMath.eval("convert(a&~b,'L')", a=r, b=b) # red and not blue # Isolate red channel: a = ImageMath.eval("convert(r&a, 'L')", r=r, a=a) # makes only red opaque g = ImageMath.eval("convert(g&0, 'L')", g=g) # make all green 0 intensity b = ImageMath.eval("convert(b&0, 'L')", b=b) # make all blue 0 intensity imRed = Image.merge("RGBA", (r, g, b, a)) # merge to get only red ############################################################################### # this part removes the axis def setup_figure(sz): # prep a figure with no axes fig = plt.figure(figsize=(sz[0], sz[1])) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.margins(0, 0) ax.axis('off') ax.xaxis.set_major_locator(plt.NullLocator()) ax.yaxis.set_major_locator(plt.NullLocator()) fig.add_axes(ax) return fig, ax
def split_merge(mode): return Image.merge(mode, lena(mode).split())
iI = intensity minI = 100 maxI = 210 minO = 0 maxO = 255 iO = (iI - minI) * (((maxO - minO) / (maxI - minI)) + minO) return iO # Create an image object imageObject = Image.open("lenna.png") # Split the red, green and blue bands from the Image multiBands = imageObject.split() # Apply point operations that does contrast stretching on each color band normalizedRedBand = multiBands[0].point(normalizeRed) normalizedGreenBand = multiBands[1].point(normalizeGreen) normalizedBlueBand = multiBands[2].point(normalizeBlue) # Create a new image from the contrast stretched red, green and blue brands normalizedImage = Image.merge( "RGB", (normalizedRedBand, normalizedGreenBand, normalizedBlueBand)) # Display the image before contrast stretching imageObject.show() # Display the image after contrast stretching normalizedImage.show()
def make_materials(ob, clump, folder, report, tex_extension = "jpg", mask_extension = "zip", animation_interval = 5): for shape in clump.shapes: # Get material mat_sign = shape.state.mat_signature mat = bpy.data.materials.get(mat_sign) if mat is None: # create material mat = bpy.data.materials.new(name=mat_sign) mat.use_nodes = True # We get the existing Principeld BSDF node, we will need it in any case bsdf = mat.node_tree.nodes["Principled BSDF"] tex = mat.node_tree.nodes.new('ShaderNodeTexImage') if shape.state.texture and folder is not None: img_path = os.path.join(folder, "%s.%s" % (shape.state.texture, tex_extension)) if shape.state.mask is not None and has_image: try: zipf = zipfile.ZipFile(os.path.join(folder, "%s.%s" % (shape.state.mask, mask_extension)), "r") except Exception as e: report({'WARNING'}, str(e)) else: name_list = zipf.namelist() bmp_dir = os.path.join(tempfile.gettempdir(), "rwx2blender") if len(name_list) == 1: os.makedirs(bmp_dir, exist_ok=True) zipf.extract(name_list[0], path = bmp_dir) # Loading RGB texture im = Image.open(img_path) w, h = im.size rgb_chans = im.convert("RGB").split() im.close() # Loading alpha mask bmp_path = os.path.join(bmp_dir, name_list[0]) im = Image.open(bmp_path) im_cpy = im.resize((w, h)) im.close() a_chan = im_cpy.split()[0].convert("L") im_cpy.close() # Merging and saving the final PNG result rgba_chans = [rgb_chans[0], rgb_chans[1], rgb_chans[2], a_chan] img_path = os.path.join(bmp_dir, "%s.%s" % (shape.state.texture, "png")) im = Image.merge("RGBA", rgba_chans) im.save(img_path) im.close() mat.blend_method = 'BLEND' tex.image = bpy.data.images.load(img_path) # Link TexImage Node to BSDF node mat.node_tree.links.new(bsdf.inputs['Base Color'], tex.outputs['Color']) mat.node_tree.links.new(bsdf.inputs['Alpha'], tex.outputs['Alpha']) # Evaluate of the texture is meant to be animated if tex.image.size[1] != tex.image.size[0] and tex.image.size[1] % tex.image.size[0] == 0: # It does: we need to add additional nodes to the shader mapping = mat.node_tree.nodes.new('ShaderNodeMapping') tex_coord = mat.node_tree.nodes.new('ShaderNodeTexCoord') mat.node_tree.links.new(tex.inputs['Vector'], mapping.outputs['Vector']) mat.node_tree.links.new(mapping.inputs['Vector'], tex_coord.outputs['UV']) # Adjust mapping of the texture nb_y_tiles = int(tex.image.size[1] / tex.image.size[0]) mapping.inputs["Scale"].default_value[1] = 1.0 / nb_y_tiles # Insert key frames, one for each step of the animation, including the loopback frame at the end for tile_idx in range(0, nb_y_tiles + 1): mapping.inputs["Location"].default_value[1] = (tile_idx % nb_y_tiles) * mapping.inputs["Scale"].default_value[1] mapping.inputs["Location"].keyframe_insert(data_path = "default_value", index = 1, frame = tile_idx * animation_interval) # Set constant interpolation to correctly warp from tile to tile fcurve = mat.node_tree.animation_data.action.fcurves[0] for kfp in fcurve.keyframe_points: kfp.interpolation = 'CONSTANT' # Loop the animation fcurve.modifiers.new('CYCLES') else: bsdf.inputs['Base Color'].default_value[:3] = shape.state.color bsdf.inputs['Alpha'].default_value = shape.state.opacity bsdf.inputs['Specular'].default_value = shape.state.surface[2] mat.diffuse_color[:3] = shape.state.color mat.diffuse_color[3] = shape.state.opacity mat.specular_color = (1.0, 1.0, 1.0) if shape.state.opacity < 1.0: mat.blend_method = 'BLEND' if shape.state.materialmode == MaterialMode.NONE: mat.use_backface_culling = True elif shape.state.materialmode == MaterialMode.NULL: mat.diffuse_color[3] = 0.0 elif shape.state.materialmode == MaterialMode.DOUBLE: mat.use_backface_culling = False if ob.data.materials: ob.data.materials.append(mat) if mat_sign not in ob.data.materials.keys(): ob.data.materials.append(mat)
def assemble(self, roboset=None, color=None, format=None, bgset=None, sizex=300, sizey=300): """ Build our Robot! Returns the robot image itself. """ # Allow users to manually specify a robot 'set' that they like. # Ensure that this is one of the allowed choices, or allow all # If they don't set one, take the first entry from sets above. if roboset == 'any': roboset = self.sets[self.hasharray[1] % len(self.sets)] elif roboset in self.sets: roboset = roboset else: roboset = self.sets[0] # Only set1 is setup to be color-seletable. The others don't have enough pieces in various colors. # This could/should probably be expanded at some point.. # Right now, this feature is almost never used. ( It was < 44 requests this year, out of 78M reqs ) if roboset == 'set1': if color in self.colors: roboset = 'set1/' + color else: randomcolor = self.colors[self.hasharray[0] % len(self.colors)] roboset = 'set1/' + randomcolor # If they specified a background, ensure it's legal, then give it to them. if bgset in self.bgsets: bgset = bgset elif bgset == 'any': bgset = self.bgsets[self.hasharray[2] % len(self.bgsets)] # If we set a format based on extension earlier, use that. Otherwise, PNG. if format is None: format = self.format # Each directory in our set represents one piece of the Robot, such as the eyes, nose, mouth, etc. # Each directory is named with two numbers - The number before the # is the sort order. # This ensures that they always go in the same order when choosing pieces, regardless of OS. # The second number is the order in which to apply the pieces. # For instance, the head has to go down BEFORE the eyes, or the eyes would be hidden. # First, we'll get a list of parts of our robot. roboparts = self._get_list_of_files(self.resourcedir + 'sets/' + roboset) # Now that we've sorted them by the first number, we need to sort each sub-category by the second. roboparts.sort(key=lambda x: x.split("#")[1]) if bgset is not None: bglist = [] backgrounds = natsort.natsorted( os.listdir(self.resourcedir + 'backgrounds/' + bgset)) backgrounds.sort() for ls in backgrounds: if not ls.startswith("."): bglist.append(self.resourcedir + 'backgrounds/' + bgset + "/" + ls) background = bglist[self.hasharray[3] % len(bglist)] # Paste in each piece of the Robot. roboimg = Image.open(roboparts[0]) roboimg = roboimg.resize((1024, 1024)) for png in roboparts: img = Image.open(png) img = img.resize((1024, 1024)) roboimg.paste(img, (0, 0), img) # If we're a BMP, flatten the image. if format == 'bmp': #Flatten bmps r, g, b, a = roboimg.split() roboimg = Image.merge("RGB", (r, g, b)) if bgset is not None: bg = Image.open(background) bg = bg.resize((1024, 1024)) bg.paste(roboimg, (0, 0), roboimg) roboimg = bg self.img = roboimg.resize((sizex, sizey), Image.ANTIALIAS) self.format = format
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')
def save(self): im = Image.open(self.document) #opens a particular image output = BytesIO() #file is written into memory im = im.resize((self.width, self.height)) if self.flip == 'horizon': im = im.transpose(Image.FLIP_LEFT_RIGHT) elif self.flip == 'vertical': im = im.transpose(Image.FLIP_TOP_BOTTOM) elif self.flip == 'NONE': pass if self.rotate == 'clock': im = im.rotate(270) elif self.rotate == 'anti': im = im.rotate(90) elif self.rotate == 'NONE': pass if self.blur == 'y': im = im.filter(ImageFilter.BLUR) elif self.blur == 'n': pass if self.effect == 1: im = im.convert('RGB') r, g, b = im.split() im = Image.merge('RGB', (r, g, b)) elif self.effect == 2: im = im.convert('RGB') r, g, b = im.split() im = Image.merge('RGB', (b, g, r)) elif self.effect == 3: im = im.convert('RGB') r, g, b = im.split() im = Image.merge('RGB', (g, r, b)) elif self.effect == 4: width, height = im.size for i in range(width): for j in range(height): r, g, b = im.getpixel((i,j)) c = int(round((r+g+b)/3)) im.putpixel((i,j),(c,c,c)) elif self.effect == 5: im = im.convert('RGB') r, g, b = im.split() im = Image.merge('RGB', (r, b, g)) elif self.effect == 6: im = im.filter(ImageFilter.FIND_EDGES) elif self.effect == 7: im = ImageOps.invert(im) elif self.effect == 8: width, height = im.size for i in range(width): for j in range(height): r, g, b = im.getpixel((i,j)) c = int((round(r+g+b)/3)) R, G, B = c+100, c+100, c im.putpixel((i, j), (R, G, B)) im.save(output, format='JPEG', quality=100) # saving the image into the file in memory output.seek(0) self.document = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.document.name.split('.')[0], 'image/jpeg', sys.getsizeof(output), None) try: this = Document.objects.get(id=self.id) if this.document == self.document: self.document = this.document else: this.document.delete(save=False) except: pass # when new image super(Document, self).save()
wx = (maxu - minu) * 0.6 wy = (maxv - minv) * 0.6 self.ims = [] for i in range(data.n): # print ids[i] im = Image.open(data.img_src[i]) im = im.resize(((im.size[0] * 100) / im.size[1], 100)) ## now make the white invisible (if you want!) im = im.convert('RGBA') source = im.split() # split the image into layers mask = im.point(lambda i: i < 255) # kluge source[3].paste(mask) # put mask into the alpha channel im = Image.merge(im.mode, source) # build a new multiband image ## self.ims.append(ImageTk.PhotoImage(im)) self.canvas.create_image(int(w / 2 + ((u[i] - cx) * w) / wx / 2), int(h / 2 + ((v[i] - cy) * h) / wy / 2), image=self.ims[-1], tags=("id:" + str(i))) def go_PCA(com1=0, com2=1): data = Generic() data.n = 26 data.img_src = [ "C:/vision/calibrialpha/calibri-" + chr(97 + i) + ".png" for i in range(data.n)
# Blinn-Phong shading (specular) phong = N.dot((toL + toO).norm()) color += rgb(1, 1, 1) * np.power(np.clip(phong, 0, 1), 50) * seelight return color class CheckeredSphere(Sphere): def diffusecolor(self, M): checker = ((M.x * 2).astype(int) % 2) == ((M.z * 2).astype(int) % 2) return self.diffuse * checker scene = [ Sphere(vec3(.75, .1, 1), .6, rgb(0, 0, 1)), Sphere(vec3(-.75, .1, 2.25), .6, rgb(.5, .223, .5)), Sphere(vec3(-2.75, .1, 3.5), .6, rgb(1, .572, .184)), CheckeredSphere(vec3(0,-99999.5, 0), 99999, rgb(.75, .75, .75), 0.25), ] r = float(w) / h # Screen coordinates: x0, y0, x1, y1. S = (-1, 1 / r + .25, 1, -1 / r + .25) x = np.tile(np.linspace(S[0], S[2], w), h) y = np.repeat(np.linspace(S[1], S[3], h), w) t0 = time.time() Q = vec3(x, y, 0) color = raytrace(E, (Q - E).norm(), scene) print ("Took", time.time() - t0) rgb = [Image.fromarray((255 * np.clip(c, 0, 1).reshape((h, w))).astype(np.uint8), "L") for c in color.components()] Image.merge("RGB", rgb).save("rt3.png")
# image.show() # 转化为灰度图形 image1 = image.convert('L') # image1.show() # 灰度图形变为二值图像,黑白图像 img2 = image1.point(lambda i: 0 if i > 160 else 255) # img2.show() # 反正图形,一般只对灰度图像做 img3 = image.point(lambda i: 255 - i) # img3.show() # 大小缩放 img4 = image1.resize((32, 32)) # img4.show() # 旋转 # 30:逆时针选择30度 , expand:旋转之后图片大小是否发生变化,True,会变化,但是图片内容不会丢失,图片整体可能会变小False不会变化,但是 # 图片内容可能会丢失。fillcolor:多于出来的位置用此指定的演示填充。 img5 = image1.rotate(30, expand=True, fillcolor=None) # img5.show() # 转置 img6 = image1.transpose(Image.FLIP_LEFT_RIGHT) # img6.show() #剪切 box = (100, 100, 1000, 200) img7 = image.crop(box) # img7.show() #分裂,组合,粘贴 r, g, b, a = image.split() g.show() b = b.point(lambda i: i * 5.5) img8 = Image.merge(image.mode, (r, g, b, a)) img8.show()
while 1: ret, img = cap.read() # find the face faces = face_cascade.detectMultiScale(img, 1.3, 5) # if a face is found for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) # subarray corresponding to the face np_face = img[y:y + h, x:x + w] # converting into PIL.Image object to resize pil_face = Image.fromarray(np_face, 'RGB') # adapter la taille à notre CNN pil_face = pil_face.resize((49, 49), resample=Image.BILINEAR) # remettre l'image et rgb b, g, r = pil_face.split() pil_face = Image.merge("RGB", (r, g, b)) # pil_face.save('face_resized.png', format='PNG') # remettre tout en np.array np_face = np.asarray(pil_face, dtype=np.uint8) print(np_face.shape) #call le predict cv2.imshow('img', img) # kill with ctr+c k = cv2.waitKey(30) & 0xff if k == 27: break
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
def sim_frame_generator(): call([ 'aws', 's3', 'sync', '--quiet', '/home/workspace/CARLASemSeg/Train', 's3://yang-carla-train' ]) frame = 100000 last_frame_time = time.time() print('initializing CARLA client connection') with make_carla_client('localhost', 2000, timeout=300) as client: try: print('CarlaClient connected !') while 1: #init settings = CarlaSettings() settings.set(SynchronousMode=True, SendNonPlayerAgentsInfo=True, NumberOfVehicles=random.choice([30, 50, 120, 200]), NumberOfPedestrians=random.choice([0, 10, 20, 30]), WeatherId=random.choice( [1, 2, 8, 1, 2, 8, 1, 2, 3, 6, 7, 8]), QualityLevel='Epic') settings.randomize_seeds() #settings.randomize_weather() camera0 = Camera('CameraRGB') camera0.set_image_size(800, 600) camera0.set_position(1.3, 0, 1.3) #camera0.FOV = 60 settings.add_sensor(camera0) camera1 = Camera('CameraSemSeg', PostProcessing='SemanticSegmentation') camera1.set_image_size(800, 600) camera1.set_position(1.3, 0, 1.3) #camera1.FOV = 60 settings.add_sensor(camera1) scene = client.load_settings(settings) number_of_player_starts = len(scene.player_start_spots) player_start = random.randint( 0, max(0, number_of_player_starts - 1)) client.start_episode(player_start) for xx in range(500): measurements, sensor_data = client.read_data() for name, measurement in sensor_data.items(): image = PImage.frombytes(mode='RGBA', size=(measurement.width, measurement.height), data=measurement.raw_data, decoder_name='raw') color = image.split() image = PImage.merge("RGB", color[2::-1]) if name == 'CameraRGB': img = image elif name == 'CameraSemSeg': seg = image img.save( '/home/workspace/CARLASemSeg/Train/CameraRGB/%07d.png' % frame, "PNG") seg.save( '/home/workspace/CARLASemSeg/Train/CameraSeg/%07d.png' % frame, "PNG") frame += 1 if (frame >= 200000): return if (frame % 100 == 0): print() print("saving frame id: {}, time:{}".format( frame, time.time())) print() fps = 1.0 / (time.time() - last_frame_time) last_frame_time = time.time() sys.stdout.write("\r" + str(fps)) sys.stdout.flush() control = measurements.player_measurements.autopilot_control control.steer += random.uniform(-0.1, 0.1) client.send_control(control) call([ 'aws', 's3', 'sync', '--quiet', '/home/workspace/CARLASemSeg/Train', 's3://yang-carla-train' ]) finally: pass
# =========================================================== # model import & setting # =========================================================== device = torch.device('cuda' if GPU_IN_USE else 'cpu') model = torch.load(args.model, map_location=lambda storage, loc: storage) model = model.to(device) data = (ToTensor()(y)).view(1, -1, y.size[1], y.size[0]) data = data.to(device) if GPU_IN_USE: cudnn.benchmark = True # =========================================================== # output and save image # =========================================================== out = model(data) out = out.cpu() out_img_y = out.data[0].numpy() out_img_y *= 255.0 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(args.output) print('output image saved to ', args.output)
def multAplha(image, factor): """Multiplicates the alpha channel of image by factor.""" channels = list(image.split()) channels[3] = channels[3].point(lambda x: x * factor) return Image.merge(image.mode, channels)
im_r.show() im_g.show() im_b.show() input() diff_r = ImageChops.difference(r, im_r) diff_r.show() input() szum = Image.open('szum.jpg') szum.show() diff_szum = ImageChops.difference(im, szum) diff_szum.show() input() im1 = Image.merge('RGB', (im_r, im_g, im_b)) im2 = Image.merge('RGB', (r, g, b)) # zamień r na im_r i sprawdź efekt im1.show() im2.show() diff_im = ImageChops.difference(im1, im2) input() im3 = Image.merge('RGB', (r, b, g)) im3.show() input() # tworzenie obrazu w odcieniach szarości w1 = 0.3 w2 = 0.8 w3 = 0.2
from PIL import Image import argparse parser = argparse.ArgumentParser() parser.add_argument("--r", type=str) parser.add_argument("--g", type=str) parser.add_argument("--b", type=str) parser.add_argument("--out", type=str) args = parser.parse_args() rImg, gImg, bImg = Image.open(args.r), Image.open(args.g), Image.open(args.b) r, _, _ = rImg.split() _, g, _ = gImg.split() _, _, b = bImg.split() outImg = Image.merge('RGB', (r, g, b)) outImg.save(args.out)
def YUV420SP_to_JPG(read_path, save_path, width, height): def _readYuvFile(filename, width, height): fp = open(filename, 'rb') uv_width = width // 2 uv_height = height // 2 Y = np.zeros((height, width), np.uint16, 'C') U = np.zeros((uv_height, uv_width), np.uint16, 'C') V = np.zeros((uv_height, uv_width), np.uint16, 'C') for m in range(height): for n in range(width): Y[m, n] = ord(fp.read(1)) for m in range(uv_height): for n in range(uv_width): V[m, n] = ord(fp.read(1)) U[m, n] = ord(fp.read(1)) fp.close() return (Y, U, V) def _yuv2rgb(Y, U, V, width, height): U = np.repeat(U, 2, 0) U = np.repeat(U, 2, 1) V = np.repeat(V, 2, 0) V = np.repeat(V, 2, 1) rf = np.zeros((height, width), float, 'C') gf = np.zeros((height, width), float, 'C') bf = np.zeros((height, width), float, 'C') rf = Y + 1.14 * (V - 128.0) gf = Y - 0.395 * (U - 128.0) - 0.581 * (V - 128.0) bf = Y + 2.032 * (U - 128.0) # rf = Y + 1.402 * (V - 128) # r # gf = Y - 0.34413 * (U - 128) - 0.71414 * (V-128) # g # bf = Y + 1.772 * (U-128) + 0 # b for m in range(height): for n in range(width): if (rf[m, n] > 255): rf[m, n] = 255 if (gf[m, n] > 255): gf[m, n] = 255 if (bf[m, n] > 255): bf[m, n] = 255 if (rf[m, n] < 0): rf[m, n] = 0 if (gf[m, n] < 0): gf[m, n] = 0 if (bf[m, n] < 0): bf[m, n] = 0 r = rf.astype(np.uint8) g = gf.astype(np.uint8) b = bf.astype(np.uint8) return (r, g, b) data = _readYuvFile(read_path, width, height) Y = data[0] RGB = _yuv2rgb(data[0], data[1], data[2], width, height) im_r = Image.fromstring('L', (width, height), RGB[0].tostring()) im_g = Image.fromstring('L', (width, height), RGB[1].tostring()) im_b = Image.fromstring('L', (width, height), RGB[2].tostring()) im_rgb = Image.merge('RGB', (im_r, im_g, im_b)) im_rgb.save(save_path)
#!/usr/bin/python3 from mss import mss from PIL import Image import sys icon = "/home/jschrod/.local/share/icons/screenlock.png" try: fn = sys.argv[1] except: sys.exit("Usage: %s [filename]" % sys.argv[0]) with mss() as screenshoter: icn = Image.open(icon, "r") img = screenshoter.grab(screenshoter.monitors[0]) img2 = Image.frombytes('RGB', img.size, img.rgb) img2 = img2.resize((int(img.size[0] / 10), int(img.size[1] / 10)), Image.BILINEAR) img2 = img2.resize(img.size) img2 = img2.convert("RGBA") mask = Image.merge("L", (icn.split()[3], )) offsetx = 0 for mon in screenshoter.monitors[1:]: img2.paste(icn, (int(offsetx + mon['width'] / 2 - icn.size[0] / 2), int(mon['height'] / 2 - icn.size[1] / 2)), mask) offsetx += mon['width'] img2.save(fn)
from PIL import Image sister = Image.open("cute.jpg") bucky = Image.open("bb.jpg") r1, g1, b1 = sister.split() r2, g2, b2 = bucky.split() new_img = Image.merge("RGB", (r2, g1, b2)) new_img.show()
def channelShift(img, delta): r, g, b = img.split() r = roll(r, delta) g = roll(g, -delta) return Image.merge("RGB", (r, g, b))
def saveToFile(self, fn, fmt=None): im = self.toPIL() if fmt is None: if not isinstance(fn, str): raise ValueError("Invalid value '%s' for fn when fmt is None" % ascii(fn)) fmt = os.path.splitext(fn)[1] if fmt.startswith('.'): fmt = fmt[1:] configPIL = self.configPIL or {} configPIL.setdefault('preConvertCB', None) preConvertCB = configPIL.pop('preConvertCB') if preConvertCB: im = preConvertCB(im) fmt = fmt.upper() if fmt in ('GIF', ): im = _convert2pilp(im) elif fmt in ('TIFF', 'TIFFP', 'TIFFL', 'TIF', 'TIFF1'): if fmt.endswith('P'): im = _convert2pilp(im) elif fmt.endswith('L'): im = _convert2pilL(im) elif fmt.endswith('1'): im = _convert2pil1(im) fmt = 'TIFF' elif fmt in ('PCT', 'PICT'): return _saveAsPICT(im, fn, fmt, transparent=configPIL.get('transparent', None)) elif fmt in ('PNG', 'BMP', 'PPM'): if fmt == 'PNG': try: from PIL import PngImagePlugin except ImportError: import PngImagePlugin elif fmt == 'BMP': try: from PIL import BmpImagePlugin except ImportError: import BmpImagePlugin elif fmt in ('JPG', 'JPEG'): fmt = 'JPEG' elif fmt in ('GIF', ): pass else: raise RenderPMError("Unknown image kind %s" % fmt) if fmt == 'TIFF': tc = configPIL.get('transparent', None) if tc: from PIL import ImageChops, Image T = 768 * [0] for o, c in zip((0, 256, 512), tc.bitmap_rgb()): T[o + c] = 255 #if isinstance(fn,str): ImageChops.invert(im.point(T).convert('L').point(255*[0]+[255])).save(fn+'_mask.gif','GIF') im = Image.merge( 'RGBA', im.split() + (ImageChops.invert( im.point(T).convert('L').point(255 * [0] + [255])), )) #if isinstance(fn,str): im.save(fn+'_masked.gif','GIF') for a, d in ('resolution', self._dpi), ('resolution unit', 'inch'): configPIL[a] = configPIL.get(a, d) configPIL.setdefault('chops_invert', 0) if configPIL.pop('chops_invert'): from PIL import ImageChops im = ImageChops.invert(im) configPIL.setdefault('preSaveCB', None) preSaveCB = configPIL.pop('preSaveCB') if preSaveCB: im = preSaveCB(im) im.save(fn, fmt, **configPIL) if not hasattr(fn, 'write') and os.name == 'mac': from reportlab.lib.utils import markfilename markfilename(fn, ext=fmt)
img = Image.open("lena.tiff") img_r, img_g, img_b = img.split() plt.figure(figsize=(10, 10)) plt.suptitle("图像基本操作", fontsize=20, color="blue") plt.subplot(221) plt.axis("off") imgr = img_r.resize((50, 50)) plt.imshow(imgr, cmap="gray") plt.title("R-缩放", fontsize=14) plt.subplot(222) imgg = img_g.transpose(Image.FLIP_LEFT_RIGHT) imggg = imgg.transpose(Image.ROTATE_270) plt.imshow(imggg, cmap="gray") plt.title("G-镜像+旋转", fontsize=14) plt.subplot(223) plt.axis("off") imgb = img_b.crop((0, 0, 300, 300)) plt.imshow(imgb, cmap="gray") plt.title("B-裁剪", fontsize=14) img_rgb = Image.merge("RGB", [img_r, img_g, img_b]) plt.subplot(224) plt.axis("off") plt.imshow(img_rgb) plt.title("RGB", fontsize=14) img_rgb.save("text.png") plt.show()
device = select_device(args.device, batch_size=1) # create model model = SRCNN().to(device) # Load state dicts model.load_state_dict(torch.load(args.weights, map_location=device)) # Open image image = Image.open(args.file).convert("YCbCr") y, cb, cr = image.split() preprocess = transforms.ToTensor() inputs = preprocess(y).view(1, -1, y.size[1], y.size[0]) inputs = inputs.to(device) with torch.no_grad(): out = model(inputs) out = out.cpu() out_image_y = out[0].detach().numpy() out_image_y *= 255.0 out_image_y = out_image_y.clip(0, 255) out_image_y = Image.fromarray(np.uint8(out_image_y[0]), mode="L") out_img_cb = cb.resize(out_image_y.size, Image.BICUBIC) out_img_cr = cr.resize(out_image_y.size, Image.BICUBIC) out_img = Image.merge("YCbCr", [out_image_y, out_img_cb, out_img_cr]).convert("RGB") # before converting the result in RGB out_img.save(f"srcnn.png")
# Now let's get the model output blob img_out = workspace.FetchBlob("27") ###################################################################### # Now, we'll refer back to the post-processing steps in PyTorch # implementation of super-resolution model # `here <https://github.com/pytorch/examples/blob/master/super_resolution/super_resolve.py>`__ # to construct back the final output image and save the image. # img_out_y = Image.fromarray(np.uint8((img_out[0, 0]).clip(0, 255)), mode='L') # get the output image follow post-processing step from PyTorch implementation final_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") # Save the image, we will compare this with the output image from mobile device final_img.save("./_static/img/cat_superres.jpg") ###################################################################### # We have finished running our mobile nets in pure Caffe2 backend and now, # let's execute the model on an Android device and get the model output. # # ``NOTE``: for Android development, ``adb`` shell is needed otherwise the # following section of tutorial will not run. # # In our first step of runnig model on mobile, we will push a native speed # benchmark binary for mobile device to adb. This binary can execute the
image = tempim h = imsize[0] w = imsize[0] elif imsize[1] > imsize[0]: tempim = np.zeros((imsize[1], imsize[1], 3), dtype='uint8') distant = (imsize[1] - imsize[0]) // 2 tempim[distant:distant + imsize[0], :, :] = image image = tempim h = imsize[1] w = imsize[1] image = np.expand_dims(image, 0) boxes = get_yolo_boxes(infer_model, image, 608, 608, # todo: change here too config['model']['anchors'], 0.5, 0.5)[0] # infer_model.predict(image) # labels = ['badhelmet', 'badshoes', 'goodhelmet', 'goodshoes', 'person'] # # draw bounding boxes on the image using labels image = draw_boxesv3(image[0], boxes, labels, 0.75) im = Image.fromarray(image.astype('uint8')) b, g, r = im.split() im = Image.merge("RGB", (r, g, b)) print(time.time() - x) im.save('/home/palm/PycharmProjects/algea/dataset/yolo_testset/' + os.path.split(filename)[1]) print('total time:', time.time() - t)
img = img.resize((224, 224)) img.save(input_image) img_ycbcr = img.convert('YCbCr') y, cb, cr = img_ycbcr.split() img_ndarray = np.asarray(y) img_4 = np.expand_dims(np.expand_dims(img_ndarray, axis=0), axis=0) imginput = img_4.astype(np.float32) / 255.0 print(imginput.shape) ort_session = onnxruntime.InferenceSession('./model.onnx') input_name = ort_session.get_inputs()[0].name ort_inputs = {input_name: imginput} ort_outs = ort_session.run(None, ort_inputs) ort_outs = np.array(ort_outs) ort_outs = ort_outs.squeeze(0) ort_outs = ort_outs.squeeze(0) print(ort_outs.shape) ort_outs *= 255.0 ort_outs = ort_outs.clip(0, 255) ort_outs = Image.fromarray(np.uint8(ort_outs[0]), mode='L') out_img = Image.merge( "YCbCr", [ ort_outs, cb.resize(ort_outs.size, Image.BICUBIC), cr.resize(ort_outs.size, Image.BICUBIC), ]).convert("RGB") plt.imshow(out_img) out_img.save(output_image) print('output image saved to ', output_image)
from PIL import Image im = Image.open("E:\OneDrive - mails.cqjtu.edu.cn\AllCode\Python\pic.jpg") r, g, b = im.split() im = Image.merge("RGB", (b, g, r)) im.show()
def InsertLSB(img, data, is_dct, is_img): '''Insert the message to be hidden into the cover image using the Least Significant Bit (LSB) method Parameters ---------- img: array Is the cover image in array format data: array Is the message (text or image) to be hidden in array format is_dct: Boolean True if the method used is Discrete Cosine Transform (DCT) is_img: Boolean True if the message to be encoded is an image ''' imgType = None global MESSAGE_CODE global BLOCKS_COUNT global TOTAL_BLOCKS_NEEDED if is_img: binData = ''.join([format(x, '09b') for x in data ]) + bin(0xFFAA)[2:] ##Sinal de fim da mensagem else: binData = bin( int(binascii.hexlify(data), 16))[2:] + bin(0xFFAA)[2:] # Sinal de fim da mensagem dataLen = len(binData) # binDataBackUp = binData if (img.mode == "RGBA"): R, G, B, A = img.split() arrayR = np.asarray(R) arrayG = np.asarray(G) arrayB = np.asarray(B) arrayA = np.asarray(A) imgType = ImageType.RGBA elif (img.mode == "L"): arrayL = np.asarray(img) imgType = ImageType.L else: img = img.convert("RGB") R, G, B = img.split() arrayR = np.asarray(R) arrayG = np.asarray(G) arrayB = np.asarray(B) imgType = ImageType.RGB print(img.size) BLOCKS_COUNT = math.ceil(dataLen / 64.0) TOTAL_BLOCKS_NEEDED = BLOCKS_COUNT utils.setProgressBar(100) imgMod = [] w = img.size[0] h = img.size[1] # In this method i'm only using 8x8 blocks, the capacity counts only for perfect 8x8 blocks capacity = (w - w % 8) * (h - h % 8) print('Tamanho Total do dado a ser inserido: ' + str(dataLen) + '\n') print( 'Quantidade de bits que podem ser modificados em uma camada da imagem: ' + str(capacity) + '\n') if (imgType == ImageType.L): if (dataLen > capacity): print( 'Imagem não possui tamanho suficiente para esconder informação \n' ) return -1 else: imgMod = encodeIMG(arrayL, binData, is_dct) imgMod = Image.fromarray(imgMod, 'L') return imgMod elif (imgType == ImageType.RGBA): # mode RGBA if (dataLen > capacity * 4): print( 'Imagem não possui tamanho suficiente para esconder informação \n' ) return -1 else: nroLayers = math.ceil(dataLen / float(capacity)) print('Número de camadas necessárias para armazenar o dado: ' + str(nroLayers) + '\n') if (nroLayers == 4): imgModR = encodeIMG(arrayR, binData[:capacity], is_dct) binData = binData[capacity:] imgModG = encodeIMG(arrayG, binData[:capacity], is_dct) binData = binData[capacity:] imgModB = encodeIMG(arrayB, binData[:capacity], is_dct) binData = binData[capacity:] imgModA = encodeIMG(arrayA, binData[:capacity], is_dct) elif (nroLayers == 3): imgModR = encodeIMG(arrayR, binData[:capacity], is_dct) binData = binData[capacity:] imgModG = encodeIMG(arrayG, binData[:capacity], is_dct) binData = binData[capacity:] imgModB = encodeIMG(arrayB, binData[:capacity], is_dct) imgModA = arrayA elif (nroLayers == 2): imgModR = encodeIMG(arrayR, binData[:capacity], is_dct) binData = binData[capacity:] imgModG = encodeIMG(arrayG, binData[:capacity], is_dct) imgModB = arrayB imgModA = arrayA elif (nroLayers == 1): imgModR = encodeIMG(arrayR, binData, is_dct) imgModG = arrayG imgModB = arrayB imgModA = arrayA R = Image.fromarray(imgModR) G = Image.fromarray(imgModG) B = Image.fromarray(imgModB) A = Image.fromarray(imgModA) imgMod = Image.merge('RGBA', (R, G, B, A)) #imgMod = np.stack((imgModR, imgModG, imgModB, imgModA)) return imgMod elif (imgType == ImageType.RGB): # mode RGB if (dataLen > capacity * 3): print( 'Imagem não possui tamanho suficiente para esconder informação \n' ) return -1 else: nroLayers = math.ceil(dataLen / float(capacity)) print('Número de camadas necessárias para armazenar o dado: ' + str(nroLayers) + '\n') if (nroLayers == 3): # print("Layer R") imgModR = encodeIMG(arrayR, binData[:capacity], is_dct) binData = binData[capacity:] # print("Layer G") imgModG = encodeIMG(arrayG, binData[:capacity], is_dct) binData = binData[capacity:] # print("Layer B") imgModB = encodeIMG(arrayB, binData[:capacity], is_dct) elif (nroLayers == 2): imgModR = encodeIMG(arrayR, binData[:capacity], is_dct) binData = binData[capacity:] imgModG = encodeIMG(arrayG, binData[:capacity], is_dct) imgModB = arrayB elif (nroLayers == 1): imgModR = encodeIMG(arrayR, binData, is_dct) imgModG = arrayG imgModB = arrayB R = Image.fromarray(imgModR) G = Image.fromarray(imgModG) B = Image.fromarray(imgModB) imgMod = Image.merge('RGB', (R, G, B)) #imgMod = np.stack((imgModR,imgModG,imgModB)) return imgMod
# Share red channel used for AO on leather sheath for specular on # solo knife, where it is used for blood elif imgtype == 'AmbientOcclusion' or imgtype == 'Specular': OR, OG, OB = imbase.split() else: print("Cannot handle image type %s" % imgtype) # merge color channels # default roughness 0.5 for Knife: 188 (0.737) is correct sRGB for 0.5 # all others: RED channel not used or AO - default is 0 (0.0) # NOTE: UE4 generated baked textures are all sRGB, even roughness etc. # which normally should have disabled sRGB. if 'Knife' in texkey: mergeimage = Image.new('RGB', (texsize, texsize), (188, 0, 0)) else: mergeimage = Image.new('RGB', (texsize, texsize), (0, 0, 0)) Xr, Xg, Xb = mergeimage.split() if 'R' in mixsuffix: Xg = RG if 'M' in mixsuffix: Xb = MB if 'O' in mixsuffix or 'S' in mixsuffix: Xr = OR img_final = Image.merge('RGB', (Xr, Xg, Xb)) outfile = '{:s}/T_{:s}{:s}_{:s}.png'.format(imagesDir, meshes[texkey], texkey, mixsuffix) print("Saving %s map to %s" % (mixsuffix, outfile)) img_final.save(outfile) sys.exit(0)