import pylab import itertools import matplotlib from scikits.learn.feature_extraction import image from scikits.learn.cluster import spectral_clustering from scikits.learn import mixture parser = optparse.OptionParser() parser.add_option("-p", "--path", dest="path") options, args = parser.parse_args() prefixes = sorted(set([x.replace("front", "HOLD").replace("back", "HOLD") for x in glob(os.path.join(options.path, "*.jpg"))])) for p in prefixes[0:1]: front = numpy.asarray(ImageOps.crop(Image.open(p.replace("HOLD", "front")))) #, 100)) #graph = image.img_to_graph(ds_front) #beta = 5 #eps = 1e-6 #graph.data = np.exp(-beta*graph.data/front.std()) + eps #N_REGIONS = 11 #labels = spectral_clustering(graph, k=N_REGIONS) #labels = labels.reshape(front.shape) sfront = front.sum(2) thresh = sfront.mean() * .7 mask = numpy.where(sfront > thresh, 0, sfront) x, y = mask.nonzero() X = numpy.asarray([x, y]).T #X = X[0:100000, :]
def generateStims(left, right): border = (615, 85, 615, 250) # Instantiate matplotlib object fig = plt.figure() # Left image ax1 = fig.add_subplot(1, 1, 1) face_l = Image.open(left) # Open and crop image from list face_l = ImageOps.crop(face_l, border) ax1.set_xticks([]) # Format border (i.e., no tick marks!) ax1.set_yticks([]) ax1.axis('off') plt.imshow(face_l) # Push image to matplotlib object # Right image ax2 = fig.add_subplot(1, 2, 2) face_r = Image.open(right) # Sim. face_r = ImageOps.crop(face_r, border) ax2.set_xticks([]) ax2.set_yticks([]) ax2.axis('off') plt.imshow(face_r) # Format and save to local directory fig.subplots_adjust(right=3) filename = "stim_{}_{}.png".format(left[7:14], right[7:14]) fig.savefig(os.path.join(output, filename), bbox_inches="tight") plt.close()
def get_current_visuals(self): self.visual_names = ['input', 'output', 'GT'] nim = getattr(self, self.visual_names[0]).shape[0] visual_ret = OrderedDict() all = [] for i in range(0, min(nim - 1, 5)): row = [] for name in self.visual_names: if isinstance(name, str): if hasattr(self, name): im = util.tensor2im( getattr(self, name).data[i:i + 1, :, :, :]) row.append(im) row = tuple(row) row = np.hstack(row) if self.isweak[i] == 0: row = ImageOps.crop(Image.fromarray(row), border=8) row = ImageOps.expand(row, border=8, fill=(0, 200, 0)) row = np.asarray(row) elif self.isfixed[i] == 1: row = ImageOps.crop(Image.fromarray(row), border=4) row = ImageOps.expand(row, border=4, fill=(0, 0, 200)) row = np.asarray(row) all.append(row) all = tuple(all) allim = np.vstack(all) return OrderedDict([(self.opt.name, allim)])
def rearrange_page(lines_split, up, bottom, num_columns, original_file, output_file): original_file = Image.open(original_file) if not os.path.exists(Path(output_file).parent): os.makedirs(Path(output_file).parent) if num_columns == 2: # Cut the left page. middle_point = np.mean(lines_split[0]) left_border = (0, up - 10, (original_file.size[0] - middle_point), 10 ) # left, up, right, bottom # ImageOps.crop(original_file, left_border).show() left_imm = ImageOps.crop(original_file, left_border) # Cut the right page. right_border = (middle_point, up - 10, -1, 10 ) # left, up, right, bottom # ImageOps.crop(original_file, border).show() right_imm = ImageOps.crop(original_file, right_border) images = [left_imm, right_imm] widths, heights = zip(*(i.size for i in images)) total_width = max(widths) max_height = sum(heights) new_im = Image.new('RGB', (total_width, max_height)) y_offset = 0 for im in images: new_im.paste(im, (0, y_offset)) y_offset += im.size[1] #new_im.show() new_im.save(output_file) elif (num_columns == 1): original_file.save(output_file) else: raise NotImplementedError return
def crop_knife(mode, img, id, ktype): if ktype == "all": if mode == "play": im = Image.open(str(img)) border = (64, 30, 64, 250) # left, up, right, bottom cropped = ImageOps.crop(im, border) cropped.save(f"{id}_cropped_playside.png", "png") os.remove(f"{id}_playside.png") elif mode == "back": im = Image.open(str(img)) border = (64, 30, 64, 250) # left, up, right, bottom cropped = ImageOps.crop(im, border) cropped.save(f"{id}_cropped_backside.png", "png") os.remove(f"{id}_backside.png") if ktype == "tiger": if mode == "play": im = Image.open(str(img)) border = (3, 75, 125, 205) # left, up, right, bottom cropped = ImageOps.crop(im, border) cropped.save(f"{id}_cropped_playside.png", "png") os.remove(f"{id}_backside.png") elif mode == "back": im = Image.open(str(img)) border = (125, 75, 3, 205) # left, up, right, bottom cropped = ImageOps.crop(im, border) cropped.save(f"{id}_cropped_backside.png", "png") os.remove(f"{id}_playside.png")
def split_pages_manually(image_path, splitting_point, save_imm=False): original_file = Image.open(image_path) if original_file.size[0] > 600: print(f"Splitting the page: {image_path}") if splitting_point is None: splitting_point = int(original_file.size[0] / 2) left_border = (0, 0, (original_file.size[0] - splitting_point), 10 ) # left, up, right, bottom # ImageOps.crop(original_file, left_border).show() left_imm = ImageOps.crop(original_file, left_border) right_border = (splitting_point, 0, -1, 10) # left, up, right, bottom # ImageOps.crop(original_file, border).show() right_imm = ImageOps.crop(original_file, right_border) images = [left_imm, right_imm] widths, heights = zip(*(i.size for i in images)) total_width = max(widths) max_height = sum(heights) new_im = Image.new('RGB', (total_width, max_height)) y_offset = 0 for im in images: new_im.paste(im, (0, y_offset)) y_offset += im.size[1] if save_imm: new_im.save(image_path) else: new_im.show() else: pass
def next_batch_nyu2(size, im_dir, indices, out_height, out_width, subdir): images = [] depths = [] f = h5py.File(im_dir) for index in indices: img_file = f['images'][index - 1] dpth_file = f['depths'][index - 1].T img_reshaped = np.transpose(img_file, (2, 1, 0)) img = Image.fromarray(img_reshaped.astype(np.uint8), 'RGB') dpth = Image.fromarray(dpth_file.astype(np.float64)) border = (8, 6, 8, 6) # left, up, right, bottom cropped_img = ImageOps.crop(img, border) cropped_dpth = ImageOps.crop(dpth, border) resized_img = cropped_img.resize((304, 228), Image.BILINEAR) resized_dpth = cropped_dpth.resize((160, 128), Image.NEAREST) resized_dpth = np.expand_dims(resized_dpth, axis=3) images.append(np.asarray(resized_img)) depths.append(np.asarray(resized_dpth)) images = np.asarray(images) depths = np.asarray(depths) return images, depths
async def _createTrigger(self, user: discord.User, mode=Modes.triggered): """Fetches the user's avatar, and creates a triggered GIF, applies additional PIL image transformations based on specified mode Parameters: ----------- user: discord.User mode: Modes Returns: -------- An io.BytesIO object containing the data for the generated trigger image """ avatarData: bytes try: async with self.session.get(AVATAR_URL.format(user), headers=self.headers) as resp: avatarData = await resp.read() except aiohttp.ClientResponseError: self.logger.error("Reading user avatar response failed!", exc_info=True) return if not avatarData: self.logger.error("No avatar data received!") return with Image.open(io.BytesIO(avatarData)) as avatar: if not avatar: return offsets = [(15, 15), (5, 10), (-15, -15), (10, -10), (10, 0), (-15, 10), (10, -5)] images = [] # if hyper mode is set if mode == Modes.reallytriggered: red_overlay = Image.new(mode="RGBA", size=avatar.size, color=(255, 0, 0, 255)) mask = Image.new(mode="RGBA", size=avatar.size, color=(255, 255, 255, 127)) avatar = Image.composite(avatar, red_overlay, mask) elif mode == Modes.hypertriggered: avatar = ImageEnhance.Color(avatar).enhance(5) avatar = ImageEnhance.Sharpness(avatar).enhance(24) avatar = ImageEnhance.Contrast(avatar).enhance(4) for xcoord, ycoord in offsets: image = ImageChops.offset(avatar, xcoord, ycoord) image = ImageOps.crop(image, 15) images.append(image) avatar = ImageOps.crop(avatar, 15) result = io.BytesIO() avatar.save( result, format="GIF", append_images=images, save_all=True, duration=25, loop=0 ) # IMPORTANT: rewind to beginning of the stream before returning result.seek(0) return result
def test_sanity(): ImageOps.autocontrast(hopper("L")) ImageOps.autocontrast(hopper("RGB")) ImageOps.autocontrast(hopper("L"), cutoff=10) ImageOps.autocontrast(hopper("L"), cutoff=(2, 10)) ImageOps.autocontrast(hopper("L"), ignore=[0, 255]) ImageOps.autocontrast(hopper("L"), mask=hopper("L")) ImageOps.autocontrast(hopper("L"), preserve_tone=True) ImageOps.colorize(hopper("L"), (0, 0, 0), (255, 255, 255)) ImageOps.colorize(hopper("L"), "black", "white") ImageOps.pad(hopper("L"), (128, 128)) ImageOps.pad(hopper("RGB"), (128, 128)) ImageOps.contain(hopper("L"), (128, 128)) ImageOps.contain(hopper("RGB"), (128, 128)) ImageOps.crop(hopper("L"), 1) ImageOps.crop(hopper("RGB"), 1) ImageOps.deform(hopper("L"), deformer) ImageOps.deform(hopper("RGB"), deformer) ImageOps.equalize(hopper("L")) ImageOps.equalize(hopper("RGB")) ImageOps.expand(hopper("L"), 1) ImageOps.expand(hopper("RGB"), 1) ImageOps.expand(hopper("L"), 2, "blue") ImageOps.expand(hopper("RGB"), 2, "blue") ImageOps.fit(hopper("L"), (128, 128)) ImageOps.fit(hopper("RGB"), (128, 128)) ImageOps.flip(hopper("L")) ImageOps.flip(hopper("RGB")) ImageOps.grayscale(hopper("L")) ImageOps.grayscale(hopper("RGB")) ImageOps.invert(hopper("1")) ImageOps.invert(hopper("L")) ImageOps.invert(hopper("RGB")) ImageOps.mirror(hopper("L")) ImageOps.mirror(hopper("RGB")) ImageOps.posterize(hopper("L"), 4) ImageOps.posterize(hopper("RGB"), 4) ImageOps.solarize(hopper("L")) ImageOps.solarize(hopper("RGB")) ImageOps.exif_transpose(hopper("L")) ImageOps.exif_transpose(hopper("RGB"))
def _splitSingle(self, imageName, image, polygons: list): height = 816 width = 1408 topLeft = (0, 0, width // 2, height // 2) topRight = (width // 2, 0, 0, height // 2) bottomLeft = (0, height // 2, width // 2, 0) bottomRight = (width // 2, height // 2, 0, 0) croppedImages = [] croppedImg = image.copy() croppedImages.append(ImageOps.crop(croppedImg, topLeft)) croppedImages.append(ImageOps.crop(croppedImg, topRight)) croppedImages.append(ImageOps.crop(croppedImg, bottomLeft)) croppedImages.append(ImageOps.crop(croppedImg, bottomRight)) # croppedImages[0].show() # croppedImages[1].show() # croppedImages[2].show() # croppedImages[3].show() croppedPolygons = collections.OrderedDict() croppedPolygons["0"] = [] croppedPolygons["1"] = [] croppedPolygons["2"] = [] croppedPolygons["3"] = [] for polygon in polygons: minXY = np.nanmin(polygon, 0) maxXY = np.nanmax(polygon, 0) #top-left crop if maxXY[0] < width // 2 and maxXY[1] < height // 2: croppedPolygons["0"].append(polygon) #top-right crop if minXY[0] >= width // 2 and maxXY[1] < height // 2: polygon[:, 0] = polygon[:, 0] - width // 2 croppedPolygons["1"].append(polygon) #bottom-left crop if maxXY[0] < width // 2 and minXY[1] >= height // 2: polygon[:, 1] = polygon[:, 1] - height // 2 croppedPolygons["2"].append(polygon) #bottom-right crop if minXY[0] >= width // 2 and minXY[1] >= height // 2: polygon[:, 0] = polygon[:, 0] - width // 2 polygon[:, 1] = polygon[:, 1] - height // 2 croppedPolygons["3"].append(polygon) #Remove crops which contain no ground truth polygon toRemove = [] tempCroppedPolygons = [] for key in croppedPolygons: if not croppedPolygons[key]: toRemove.append(int(key)) else: tempCroppedPolygons.append(croppedPolygons[key]) toRemove.sort(reverse=True) for i in range(len(toRemove)): croppedImages.pop(toRemove[i]) return croppedImages, tempCroppedPolygons
def __same_inner(self, image1: Image, image2: Image, show=None) -> bool: # Cropping borders. crop1 = ImageOps.crop(image1, border=55) crop2 = ImageOps.crop(image2, border=55) if self.__are_equal(crop1, crop2, show): return True return False
async def _createTrigger(self, user, mode=Modes.triggered): """Fetches the user's avatar, and creates a triggered GIF, applies additional PIL image transformations based on specified mode Parameters: ----------- user: discord.Member mode: Mode Returns: -------- savePath: str, or None """ path = os.path.join(self.saveFolder, "{}.png".format(user.id)) savePath = os.path.join(self.saveFolder, "{}-trig.gif".format(user.id)) opener = urllib.request.build_opener() # We need a custom header or else we get a HTTP 403 Unauthorized opener.addheaders = [("User-agent", "Mozilla/5.0")] urllib.request.install_opener(opener) try: urllib.request.urlretrieve(AVATAR_URL.format(user), path) except urllib.request.ContentTooShortError: return None except urllib.error.HTTPError: # Use the default. urllib.request.urlretrieve(user.default_avatar_url, path) avatar = Image.open(path) if not avatar: return offsets = [(15, 15), (5, 10), (-15, -15), (10, -10), (10, 0), (-15, 10), (10, -5)] images = [] # if hyper mode is set if mode == Modes.reallytriggered: red_overlay = Image.new(mode="RGBA", size=avatar.size, color=(255, 0, 0, 255)) mask = Image.new(mode="RGBA", size=avatar.size, color=(255, 255, 255, 127)) avatar = Image.composite(avatar, red_overlay, mask) elif mode == Modes.hypertriggered: avatar = ImageEnhance.Color(avatar).enhance(5) avatar = ImageEnhance.Sharpness(avatar).enhance(24) avatar = ImageEnhance.Contrast(avatar).enhance(4) for xcoord, ycoord in offsets: image = ImageChops.offset(avatar, xcoord, ycoord) image = ImageOps.crop(image, 15) images.append(image) avatar = ImageOps.crop(avatar, 15) avatar.save( savePath, format="GIF", append_images=images, save_all=True, duration=25, loop=0 ) return savePath
def get_full_page_screenshot_with_fixed_header(driver): total_width = driver.execute_script("return document.body.offsetWidth") total_height = driver.execute_script("return document.body.parentNode.scrollHeight") viewport_width = driver.execute_script("return document.body.clientWidth") viewport_height = driver.execute_script("return window.innerHeight") pixel_ratio = driver.execute_script("return window.devicePixelRatio") header_height = driver.execute_script("return document.getElementsByClassName('s·header')[0].offsetHeight") print("Total: ({0}, {1}), Viewport: ({2},{3}), PixelRatio: {4}".format(total_width, total_height, viewport_width, viewport_height, pixel_ratio)) time.sleep(5) slice_index = 0 driver.get_screenshot_as_file('part_{}.png'.format(slice_index)) driver.execute_script("document.getElementsByClassName('s·header')[0].style.boxShadow = 'none'") # hide shadow height_without_header = viewport_height - header_height for slice_index in range(1, int(total_height / height_without_header)): driver.execute_script('window.scrollBy(0, {})'.format(height_without_header)) time.sleep(1) driver.get_screenshot_as_file('part_{}.png'.format(slice_index)) border = (0, header_height * pixel_ratio, 0, 0) # left, up, right, bottom img = Image.open('part_{}.png'.format(slice_index)) img = ImageOps.crop(img, border) img.save('part_{}.png'.format(slice_index)) remaining_height = (total_height - viewport_height) % (viewport_height - 104) slice_index += 1 driver.execute_script('window.scrollBy(0, {})'.format(height_without_header)) time.sleep(0.5) driver.get_screenshot_as_file('part_{}.png'.format(slice_index)) border = (0, (viewport_height - remaining_height) * pixel_ratio, 0, 0) # left, up, right, bottom img = Image.open('part_{}.png'.format(slice_index)) img = ImageOps.crop(img, border) img.save('part_{}.png'.format(slice_index)) images = [Image.open('part_{}.png'.format(image_index)) for image_index in range(slice_index+1)] widths, heights = zip(*(i.size for i in images)) total_width = max(widths) max_height = sum(heights) new_im = Image.new('RGB', (total_width, max_height)) y_offset = 0 for im in images: new_im.paste(im, (0, y_offset)) os.remove(im.filename) y_offset += im.size[1] return new_im # .save('full_screenshot.png')
def saveas(self): x=np.random.randn() filename="image"+str(x) #savename = 'im_{0:0>6}'.format(i) ImageGrab.grab(()).save("Z:style/style_transfer/media/"+filename + '.jpg') fp = open("Z:style/style_transfer/media/"+filename+".jpg","rb") img = PIL.Image.open(fp) border = (250, 250, 200, 10) fname= "img"+str(x)# left, up, right, bottom ImageOps.crop(img, border).save("Z:style/style_transfer/media/" +fname+".jpg")
def _check_assets(asset_type): ''' check appropriate asset_type from exiting image and return a string''' if asset_type == 'gold': crop_tpl = (1020, 0, 195, 660) elif asset_type == 'cash': crop_tpl = (860, 0, 310, 660) elif asset_type == 'skips': crop_tpl = (758, 0, 470, 660) ImageOps.crop(Image.open('tmp/screen.png'), crop_tpl).save('tmp/screen_cropped.png') print(crop_tpl) return pytesseract.image_to_string(Image.open('tmp/screen_cropped.png'), lang='eng', config='--psm 7').lower().strip()
def crop_glove(mode, img, id): if mode == "play": im = Image.open(str(img)) border = (128, 50, 128, 350) # left, up, right, bottom cropped = ImageOps.crop(im, border) cropped.save(f"{id}_cropped_playside.png", "png") os.remove(f"{id}_playside.png") elif mode == "back": im = Image.open(str(img)) border = (64, 50, 64, 350) # left, up, right, bottom cropped = ImageOps.crop(im, border) cropped.save(f"{id}_cropped_backside.png", "png") os.remove(f"{id}_backside.png")
def _get_pos_and_sec(): _capture_and_pull_screenshot() # import pdb;pdb.set_trace() for crop_tpl in [(953, 20, 80, 660), ]: ImageOps.crop(Image.open('tmp/screen.png'), crop_tpl).save('tmp/screen_cropped.png') result_lst = pytesseract.image_to_string(Image.open('tmp/screen_cropped.png')).lower().strip().split() if 'seconds' in result_lst or 'remaining' in result_lst: try: return (1260, 10), int(result_lst[0]) except: pass return (1260, 10), 30
def test_sanity(self): ImageOps.autocontrast(hopper("L")) ImageOps.autocontrast(hopper("RGB")) ImageOps.autocontrast(hopper("L"), cutoff=10) ImageOps.autocontrast(hopper("L"), ignore=[0, 255]) ImageOps.autocontrast_preserve(hopper("L")) ImageOps.autocontrast_preserve(hopper("RGB")) ImageOps.autocontrast_preserve(hopper("L"), cutoff=10) ImageOps.autocontrast_preserve(hopper("L"), ignore=[0, 255]) ImageOps.colorize(hopper("L"), (0, 0, 0), (255, 255, 255)) ImageOps.colorize(hopper("L"), "black", "white") ImageOps.crop(hopper("L"), 1) ImageOps.crop(hopper("RGB"), 1) ImageOps.deform(hopper("L"), self.deformer) ImageOps.deform(hopper("RGB"), self.deformer) ImageOps.equalize(hopper("L")) ImageOps.equalize(hopper("RGB")) ImageOps.expand(hopper("L"), 1) ImageOps.expand(hopper("RGB"), 1) ImageOps.expand(hopper("L"), 2, "blue") ImageOps.expand(hopper("RGB"), 2, "blue") ImageOps.fit(hopper("L"), (128, 128)) ImageOps.fit(hopper("RGB"), (128, 128)) ImageOps.flip(hopper("L")) ImageOps.flip(hopper("RGB")) ImageOps.grayscale(hopper("L")) ImageOps.grayscale(hopper("RGB")) ImageOps.invert(hopper("L")) ImageOps.invert(hopper("RGB")) ImageOps.mirror(hopper("L")) ImageOps.mirror(hopper("RGB")) ImageOps.posterize(hopper("L"), 4) ImageOps.posterize(hopper("RGB"), 4) ImageOps.solarize(hopper("L")) ImageOps.solarize(hopper("RGB"))
def _pad_crop_resize(self, detection_img): template_img, detection_img = self.image, detection_img w, h = template_img.size cx, cy, tw, th = self.box[0], self.box[1], self.box[2], self.box[3] p = round((tw + th)/2, 2) template_square_size = int(np.sqrt((tw + p)*(th + p))) #a detection_square_size = int(template_square_size * 2) #A =2a # pad detection_lt_x, detection_lt_y = cx - detection_square_size//2, cy - detection_square_size//2 detection_rb_x, detection_rb_y = cx + detection_square_size//2, cy + detection_square_size//2 left = -detection_lt_x if detection_lt_x < 0 else 0 top = -detection_lt_y if detection_lt_y < 0 else 0 right = detection_rb_x - w if detection_rb_x > w else 0 bottom = detection_rb_y - h if detection_rb_y > h else 0 padding = tuple(map(int, [left, top, right, bottom])) new_w, new_h = left + right + w, top + bottom + h # pad load self.ret['padding'] = padding self.ret['new_template_img_padding_size'] = (new_w, new_h) self.ret['new_template_img_padding'] = ImageOps.expand(template_img, border=padding, fill=self.ret['mean_template']) self.ret['new_detection_img_padding']= ImageOps.expand(detection_img, border=padding, fill=self.ret['mean_detection']) # crop tl = cx + left - template_square_size//2 tt = cy + top - template_square_size//2 tr = new_w - tl - template_square_size tb = new_h - tt - template_square_size self.ret['template_cropped'] = ImageOps.crop(self.ret['new_template_img_padding'].copy(), (tl, tt, tr, tb)) dl = np.clip(cx + left - detection_square_size//2, 0, new_w - detection_square_size) dt = np.clip(cy + top - detection_square_size//2, 0, new_h - detection_square_size) dr = np.clip(new_w - dl - detection_square_size, 0, new_w - detection_square_size) db = np.clip(new_h - dt - detection_square_size, 0, new_h - detection_square_size ) self.ret['detection_cropped']= ImageOps.crop(self.ret['new_detection_img_padding'].copy(), (dl, dt, dr, db)) self.ret['detection_tlcords_of_original_image'] = (cx - detection_square_size//2 , cy - detection_square_size//2) self.ret['detection_tlcords_of_padding_image'] = (cx - detection_square_size//2 + left, cy - detection_square_size//2 + top) self.ret['detection_rbcords_of_padding_image'] = (cx + detection_square_size//2 + left, cy + detection_square_size//2 + top) # resize self.ret['template_cropped_resized'] = self.ret['template_cropped'].copy().resize((127, 127)) self.ret['detection_cropped_resized']= self.ret['detection_cropped'].copy().resize((256, 256)) self.ret['template_cropprd_resized_ratio'] = round(127/template_square_size, 2) self.ret['detection_cropped_resized_ratio'] = round(256/detection_square_size, 2)
async def _createTrigger(self, user): """Fetches the user's avatar, and creates a triggered GIF Parameters: ----------- user: discord.Member Returns: -------- savePath: str, or None """ path = "{}{}.png".format(SAVE_FOLDER, user.id) savePath = "{}{}-trig.gif".format(SAVE_FOLDER, user.id) opener = urllib.request.build_opener() # We need a custom header or else we get a HTTP 403 Unauthorized opener.addheaders = [("User-agent", "Mozilla/5.0")] urllib.request.install_opener(opener) try: urllib.request.urlretrieve(AVATAR_URL.format(user), path) except urllib.request.ContentTooShortError: return None except urllib.error.HTTPError: # Use the default. urllib.request.urlretrieve(user.default_avatar_url, path) avatar = Image.open(path) if not avatar: return offsets = [(15, 15), (5, 10), (-15, -15), (10, -10), (10, 0), (-15, 10), (10, -5)] images = [] for xcoord, ycoord in offsets: image = ImageChops.offset(avatar, xcoord, ycoord) image = ImageOps.crop(image, 15) images.append(image) avatar = ImageOps.crop(avatar, 15) avatar.save(savePath, format="GIF", append_images=images, save_all=True, duration=25, loop=0) return savePath
def test_sanity(): ImageOps.autocontrast(lena("L")) ImageOps.autocontrast(lena("RGB")) ImageOps.autocontrast(lena("L"), cutoff=10) ImageOps.autocontrast(lena("L"), ignore=[0, 255]) ImageOps.colorize(lena("L"), (0, 0, 0), (255, 255, 255)) ImageOps.colorize(lena("L"), "black", "white") ImageOps.crop(lena("L"), 1) ImageOps.crop(lena("RGB"), 1) ImageOps.deform(lena("L"), deformer) ImageOps.deform(lena("RGB"), deformer) ImageOps.equalize(lena("L")) ImageOps.equalize(lena("RGB")) ImageOps.expand(lena("L"), 1) ImageOps.expand(lena("RGB"), 1) ImageOps.expand(lena("L"), 2, "blue") ImageOps.expand(lena("RGB"), 2, "blue") ImageOps.fit(lena("L"), (128, 128)) ImageOps.fit(lena("RGB"), (128, 128)) ImageOps.fit(lena("RGB").resize((1, 1)), (35, 35)) ImageOps.flip(lena("L")) ImageOps.flip(lena("RGB")) ImageOps.grayscale(lena("L")) ImageOps.grayscale(lena("RGB")) ImageOps.invert(lena("L")) ImageOps.invert(lena("RGB")) ImageOps.mirror(lena("L")) ImageOps.mirror(lena("RGB")) ImageOps.posterize(lena("L"), 4) ImageOps.posterize(lena("RGB"), 4) ImageOps.solarize(lena("L")) ImageOps.solarize(lena("RGB")) success()
def cropp(img): """takes a part of the image based on the coordenades of area""" print("De que forma deseas cortar la imagen") print("1.cuadrado\n2.definir area") h = input("Seleccione una opcion:") try: print("Tamaño de la imagen escogida") print(img.size) if h == "1": val = input("Seleccione el valor a cortar:") cropped_img = ImageOps.crop(img, border=int(val)) elif h == "2": prim = input( "Seleccione el primer valor 1 arriba izquierda (hacia derecha):" ) seg = input( "Seleccione el segundo valor 2 arriba izquierda (hacia abajo):" ) ter = input( "Seleccione el tercer valor 3 abajo derecha (hacia derecha):") cuar = input( "Seleccione el cuarto valor 4 abajo derecha (hacia abajo):") area = (int(prim), int(seg), int(ter), int(cuar)) cropped_img = img.crop(area) print(cropped_img.size) cropped_img.show() yn = input("Quieres guardar(s/n):") saveimg(yn, cropped_img) except: print("El area elegida excede el tamaño de la imagen")
def split_video_frames_v3(images_path): video_frames = [] frames = [] img_paths = sorted(os.listdir(images_path))[1:] for i, img_path in enumerate(img_paths): img = Image.open(images_path + '/' + img_path) img = ImageOps.crop(img, 130) img = np.array(img.resize([352, 288]))[:, :, :3] img = img / 255 frames.append(img) frames = np.array(frames).reshape([-1, 288, 352, 3]) for i, frame in enumerate(frames): plt.imsave('./Dataset/i_{:05d}.png'.format(i), frame) mean_img = np.mean(frames[::2], 0) frames = frames - mean_img for frame_index in range(len(frames)): try: video_frames.append( np.append(frames[frame_index], frames[frame_index + 1], axis=2)) except IndexError: print("Dataset prepared!") break video_frames = np.array(video_frames).reshape([-1, 288, 352, 6]) return video_frames
def __init__(self, path, resize = False, enhance = False): ''' Class Image Analizer - Parameters path: path to the image file resize: True or False, if True, it resizes an image by 10% enhance: True or False, if True it enhances the contrast of an image by 2 ''' self.path = path self.name = path.split('/')[1].split(".", 1)[0] self.img = Image.open(path) self.pix = self.img.load() self.size = self.img.size if resize == True: self.img = ImageOps.crop(self.img, border = self.size[0]*0.1) self.size = self.img.size if enhance == True: enh = ImageEnhance.Contrast(self.img) self.img = enh.enhance(2) self.total_pixels = self.size[0]*self.size[1] self.pixel_values = list(self.img.getdata()) self.colors = np.NaN self.pixel_label = np.NaN
def __remove_border(self, image: Image, border=None) -> Image: if border is None: border = 55 crop = ImageOps.crop(image, border=border) return crop
def save(self, *args, **kwargs): # Opening uploaded image img = Image.open(self.avatar) output = BytesIO() output_preview = BytesIO() # Resize image img = img.resize((225, 225)) preview = ImageOps.crop(img, (82, 82, 83, 83)) # Save to the output img.save(output, format='PNG', quality=100) preview.save(output_preview, format='PNG', quality=100) output.seek(0) output_preview.seek(0) self.avatar = InMemoryUploadedFile( output, 'ImageField', '%s.png' % self.avatar.name.split('.')[0], 'image/png', sys.getsizeof(output), None) self.avatar_preview = InMemoryUploadedFile( output_preview, 'ImageField', 'avatars_preview/{username}.png'.format(username=self.username), 'image/png', sys.getsizeof(output_preview), None) super(CustomUser, self).save(*args, **kwargs)
def createMask(imageIn, threshold=10, fillHoles=True, backgroundColor=255, blurRadius=0.0, maskScale=1.0): """ Given an image, create a mask by locating the pixels that are not the backgroundColor (within a threshold). @param threshold How far away from the backgroundColor a pixel must be to be included in the mask @param fillHoles If true, the inside of the mask will be filled in. This is useful if the inside of objects might contain the background color @param backgroundColor the background color. @param blurRadius If set to some fraction > 0.0, then the edges of the mask will be blurred using a blur radius which is this fraction of the image size. @param maskScale If set to < 1.0, then the effective size of the object (the area where the mask includes the object) will be scaled down by this amount. This can be useful when the outside of the object contains some noise that you want to trim out and not include in the mask. @retval the mask as a PIL 'L' image, where 255 is areas that include the object, and 0 are areas that are background. If blurRadius is > 0, then it will also contain values between 0 and 255 which act as compositing values. """ image = imageIn.convert('L') bwImage = image.point(lambda x: (abs(x - backgroundColor) > threshold) * 255) if not fillHoles: mask = bwImage else: bwImage = ImageOps.expand(bwImage, 1, fill=0) maskColor = 128 ImageDraw.floodfill(bwImage, (0, 0), maskColor) mask = bwImage.point(lambda x: (x != maskColor) * 255) mask = ImageOps.crop(mask, 1) # Are we reducing the object size? if maskScale < 1.0: newSize = [int(x * maskScale) for x in mask.size] reducedMask = mask.resize(newSize, Image.ANTIALIAS) sizeDiff = numpy.array(mask.size) - numpy.array(newSize) pos = [int(x / 2) for x in sizeDiff] mask = ImageChops.constant(mask, 0) mask.paste(reducedMask, tuple(pos)) # Blur the mask if blurRadius > 0.0: radius = int(round(blurRadius * (mask.size[0] + mask.size[1]) / 2)) if radius > 1: mask = blur(mask, radius=radius, edgeColor=0) else: import pdb pdb.set_trace() return mask
def solar(): image1 = Image.open(image) image2 = ImageOps.crop(image1, image1.size[1] // 4) # dividing height of image by 4 image1.show() image2.show() image3 = ImageOps.solarize(image2, 4) # dividing height of image by 4 image3.show()
def get_current_visuals(self): t= time.time() nim = self.input_img.shape[0] visual_ret = OrderedDict() all =[] for i in range(0,min(nim-1,5)): row=[] for name in self.visual_names: if isinstance(name, str): if hasattr(self,name): im = util.tensor2im(getattr(self, name).data[i:i+1,:,:,:]) row.append(im) row=tuple(row) row = np.hstack(row) if hasattr(self,'isreal'): if self.isreal[i] == 0: row = ImageOps.crop(Image.fromarray(row),border =5) row = ImageOps.expand(row,border=5,fill=(0,200,0)) row = np.asarray(row) all.append(row) all = tuple(all) allim = np.vstack(all) return OrderedDict([(self.opt.name,allim)])
def generate_puzzle_blocks(self): # deal with precission and rounding error later self.block_width = self.img_src.width // self.num_col self.block_height = self.img_src.height // self.num_row for i in range(self.num_row): for j in range(self.num_col): # omit the last block (right corner) if i == self.num_row - 1 and j == self.num_col - 1: break coord = (j * self.block_width, i * self.block_height,\ (j + 1) * self.block_width, (i + 1) * self.block_height) print(coord) # crop to blocks and create gaps between blocks for visual guidance cropped_img = self.img_src.crop(coord) stripped_border = ImageOps.crop(cropped_img, border=1) # add_border = ImageOps.expand(strip_border, border=1) # tk_img = ImageTk.PhotoImage(add_border) tk_img = ImageTk.PhotoImage(stripped_border) self.cropped_imgs.append(tk_img) block = self.canv.create_image(coord[0], coord[1], anchor='nw', image=tk_img) self.blocks.append(block)
def __call__(self, img): # flip the img by color(0<-->255) ==> then we can use methods to crop the image img_flip = ImageOps.invert(img) # sum up the pixels by row/col, to capture the attention area row_sum = np.sum(img_flip, axis=1)[:, 0] col_sum = np.sum(img_flip, axis=0)[:, 0] # get the index of the attention area position row_min = (row_sum != 0).argmax() row_max = (row_sum != 0)[::-1].argmax() col_min = (col_sum != 0).argmax() col_max = (col_sum != 0)[::-1].argmax() # crop the attention area im_attention = ImageOps.crop(img, (col_min, row_min, col_max, row_max)) # get the shape of the new image row, col = im_attention.size # create the new image # if equal, make a square image # if not, make a rectangle if self.equal: if self.deep: im_new = Image.new(img.mode, (420, 420), color='white') im_new.paste(im_attention, (int(210-row/2), int(210-col/2))) else: # create a new image -- white im_new = Image.new(img.mode, (max(row, col), max(row, col)), color='white') # fit the attention area into the new image, on center if row > col: im_new.paste(im_attention, (0, int((row - col)/2))) else: im_new.paste(im_attention, (int((col - row)/2), 0)) else: im_new = im_attention return im_new
def random_crop(img, size=[32, 32]): img_size = img.size rnd_x = np.random.randint(0, img_size[0] - size[0]) rnd_y = np.random.randint(0, img_size[1] - size[1]) new_img = ImageOps.crop(img, (rnd_x, rnd_y, img_size[0] - size[0] - rnd_x, img_size[1] - size[1] - rnd_y)) return new_img
def __call__(self, array): assert len(array.shape) == 3 and array.shape[2] == 3 image_array = skimage.img_as_ubyte(array) image = Image.fromarray(image_array, 'RGB') image = ImageOps.crop(image, self._buffer) image = image.convert('RGBA') return image
def createMask(imageIn, threshold=10, fillHoles=True, backgroundColor=255, blurRadius=0.0, maskScale=1.0): """ Given an image, create a mask by locating the pixels that are not the backgroundColor (within a threshold). @param threshold How far away from the backgroundColor a pixel must be to be included in the mask @param fillHoles If true, the inside of the mask will be filled in. This is useful if the inside of objects might contain the background color @param backgroundColor the background color. @param blurRadius If set to some fraction > 0.0, then the edges of the mask will be blurred using a blur radius which is this fraction of the image size. @param maskScale If set to < 1.0, then the effective size of the object (the area where the mask includes the object) will be scaled down by this amount. This can be useful when the outside of the object contains some noise that you want to trim out and not include in the mask. @retval the mask as a PIL 'L' image, where 255 is areas that include the object, and 0 are areas that are background. If blurRadius is > 0, then it will also contain values between 0 and 255 which act as compositing values. """ image = imageIn.convert('L') bwImage = image.point(lambda x: (abs(x - backgroundColor) > threshold) * 255) if not fillHoles: mask = bwImage else: bwImage = ImageOps.expand(bwImage, 1, fill=0) maskColor = 128 ImageDraw.floodfill(bwImage, (0, 0), maskColor) mask = bwImage.point(lambda x: (x != maskColor) * 255) mask = ImageOps.crop(mask, 1) # Are we reducing the object size? if maskScale < 1.0: newSize = [int(x * maskScale) for x in mask.size] reducedMask = mask.resize(newSize, Image.ANTIALIAS) sizeDiff = numpy.array(mask.size) - numpy.array(newSize) pos = [int(x / 2) for x in sizeDiff] mask = ImageChops.constant(mask, 0) mask.paste(reducedMask, tuple(pos)) # Blur the mask if blurRadius > 0.0: radius = int(round(blurRadius * (mask.size[0] + mask.size[1]) / 2)) if radius > 1: mask = blur(mask, radius=radius, edgeColor=0) else: import pdb; pdb.set_trace() return mask
def crop(image, mode=None, all=0, left=0, right=0, top=0, bottom=0): if mode == _t('Auto'): image = auto_crop(image) elif mode == _t('All'): image = ImageOps.crop(image, border=all) else: w, h = image.size box = ( left, top, w - right, h - bottom) image = image.crop(box) return image
def css_inject_images(stylesheet,sourceDir): injectedImages = {} injectedImageNames = [] index=0 def get_val(val): return int( re.match(r'[\-0-9]+','%s' % val).group() ) for rule in stylesheet.cssRules: if not rule.type == CSSRule.STYLE_RULE : continue style = rule.style backgroundImage = style.getPropertyValue('background-image', True) backgroundPosition = style.getPropertyValue('background-position', True) if not backgroundImage : background = style.getPropertyValue('background', True) backgroundProperties = background.split(' ') if len( backgroundProperties ) >= 3 and re.match( r"url\([^)]+\)", backgroundProperties[0] ) : backgroundImage = backgroundProperties[0] if "px" in backgroundProperties[1] and "px" in backgroundProperties[2] : backgroundPosition = tuple( -get_val(n) for n in backgroundProperties[1:3] ) else: sys.exit('Unable to process background position properties, %s' % background ) #print ', '.join( backgroundProperties ) if backgroundImage : backgroundImageURL = re.match( r"url\(([^)]+)\)", backgroundImage ).group(1) isPNG = ".png" in backgroundImageURL.lower() imagePath = os.path.realpath( os.path.join( sourceDir,backgroundImageURL ) ) name = backgroundImageURL if not os.path.isfile( imagePath ) : sys.exit('Referenced image file not found %s ' % backgroundImageURL) image = Image.open(imagePath) #print '1. writing %s' % os.path.relpath( imagePath ) #print '2. %d,%d' % image.size if backgroundPosition: width = get_val( style.getPropertyValue("width") ) height = get_val( style.getPropertyValue("height") ) dimensions = image.size bounds = backgroundPosition + (width,height) #print("3. bounds %d,%d %d,%d,%d,%d " % ( bounds + (width,height) ) ) borders = ( bounds[0],bounds[1],max( 0,dimensions[0]-bounds[2]-bounds[0] ), max( 0,dimensions[1]-bounds[3]-bounds[1]) ); image = ImageOps.crop( image, borders ) name = '%s,%d,%d,%d,%d' % ( (backgroundImageURL,)+borders ) #print( "4. cropping %d, %d, %d, %d" % borders ) output = io.BytesIO() base64Output = io.BytesIO() format='png' if isPNG else 'jpeg' image.save( output, format=format.upper() ) output.seek(0) base64.encode( output, base64Output ) base64Output.seek(0) imageTemplatePlaceholder = 'url($image%d)' % index base64EncodedImage = '"data:image/%s;base64,%s"' % (format,base64Output.getvalue()) injectedImages['image%d' % index] = base64EncodedImage index+=1 base64Output.close() output.close() style.setProperty('background-image', imageTemplatePlaceholder ) style.removeProperty('background-position',True) style.removeProperty('background',normalize=True) if name in injectedImageNames : sys.stderr.write('WARNING: Image already injected : %s' % name ) else : injectedImageNames.append( name ) return Template(stylesheet.cssText).safe_substitute( injectedImages )
def apply_unborder(pixbuf): width,height = pixbuf.get_width(),pixbuf.get_height() y = ImageOps.crop(Image.frombytes(K.ImageConstants.RGB_SHORT_NAME,(width,height),pixbuf.get_pixels() ),1) return I.fromImageToPixbuf(y)
def remove_border(self, border_size=0): """ Remove border from image. """ actual_value = float(border_size)/100 * 200 self.output = ImageOps.crop(self.output, int(actual_value)) self.add_effect('zoom')
from PIL import Image, ImageOps im = Image.open('asdf.png') im = ImageOps.crop(im,4) bordered_im = ImageOps.expand(im, 3, (255,255,255)) new_im = ImageOps.expand(bordered_im, 1, (206,206,206)) new_im.save('asdfasdf.png', 'png')
def get_cropped_tiles(img, border=112): new_im = ImageOps.crop(Image.fromarray(img), border=border) paddedimg = np.array(new_im) padded_tiles = get_tile_images(paddedimg) return padded_tiles
from PIL import ImageFilter from PIL import ImageOps from PIL import Image import os.path import os mywidth = 320 for afile in os.listdir('/some/directory'): path = os.path.join('/some/directory', afile) if afile.endswith('.jpg'): img = PIL.Image.open(path) wpercent = (mywidth / float(img.size[0])) hsize = int((float(img.size[1]) * float(wpercent))) xlimg = img.resize((mywidth, hsize), PIL.Image.ANTIALIAS) xlimg = ImageOps.crop(xlimg, border=10) source = xlimg.split() R, G, B = 0, 1, 2 mask = source[B].point(lambda i: i + 100) out = source[G].point(lambda i: i + 25) source[G].paste(out, None, mask) mask = source[B].point(lambda i: i + 100) out = source[R].point(lambda i: i + 35) source[R].paste(out, None, mask) xlimg = Image.merge(xlimg.mode, source) sharpener = ImageEnhance.Sharpness(xlimg) xlimg = sharpener.enhance(1) contraster = ImageEnhance.Contrast(xlimg) xlimg = contraster.enhance(1.2) colorizer = ImageEnhance.Color(xlimg) xlimg = colorizer.enhance(1.5)
def remove_bbox(im, border, background=WHITE): im_copy = im.copy() im_copy = ImageOps.crop(im_copy, border=border) return ImageOps.expand(im_copy, border=border, fill=background)
def test_sanity(self): ImageOps.autocontrast(hopper("L")) ImageOps.autocontrast(hopper("RGB")) ImageOps.autocontrast(hopper("L"), cutoff=10) ImageOps.autocontrast(hopper("L"), ignore=[0, 255]) ImageOps.autocontrast_preserve(hopper("L")) ImageOps.autocontrast_preserve(hopper("RGB")) ImageOps.autocontrast_preserve(hopper("L"), cutoff=10) ImageOps.autocontrast_preserve(hopper("L"), ignore=[0, 255]) ImageOps.colorize(hopper("L"), (0, 0, 0), (255, 255, 255)) ImageOps.colorize(hopper("L"), "black", "white") ImageOps.crop(hopper("L"), 1) ImageOps.crop(hopper("RGB"), 1) ImageOps.deform(hopper("L"), self.deformer) ImageOps.deform(hopper("RGB"), self.deformer) ImageOps.equalize(hopper("L")) ImageOps.equalize(hopper("RGB")) ImageOps.expand(hopper("L"), 1) ImageOps.expand(hopper("RGB"), 1) ImageOps.expand(hopper("L"), 2, "blue") ImageOps.expand(hopper("RGB"), 2, "blue") ImageOps.fit(hopper("L"), (128, 128)) ImageOps.fit(hopper("RGB"), (128, 128)) ImageOps.flip(hopper("L")) ImageOps.flip(hopper("RGB")) ImageOps.grayscale(hopper("L")) ImageOps.grayscale(hopper("RGB")) ImageOps.invert(hopper("L")) ImageOps.invert(hopper("RGB")) ImageOps.mirror(hopper("L")) ImageOps.mirror(hopper("RGB")) ImageOps.posterize(hopper("L"), 4) ImageOps.posterize(hopper("RGB"), 4) ImageOps.solarize(hopper("L")) ImageOps.solarize(hopper("RGB"))