我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用PIL.Image.BILINEAR。
def __call__(self, img, mask): if self.padding > 0: img = ImageOps.expand(img, border=self.padding, fill=0) mask = ImageOps.expand(mask, border=self.padding, fill=0) assert img.size == mask.size w, h = img.size th, tw = self.size if w == tw and h == th: return img, mask if w < tw or h < th: return img.resize((tw, th), Image.BILINEAR), mask.resize((tw, th), Image.NEAREST) x1 = random.randint(0, w - tw) y1 = random.randint(0, h - th) return img.crop((x1, y1, x1 + tw, y1 + th)), mask.crop((x1, y1, x1 + tw, y1 + th))
def remove_line(giffile,savepath): (img,pixdata) = open_img(giffile) for x in range(img.size[0]): for y in range(img.size[1]): if pixdata[x,y][0]<8 or pixdata[x,y][1]<6 or pixdata[x,y][2]<8 or (pixdata[x,y][0]+pixdata[x,y][1]+pixdata[x,y][2])<=30: if y==0: pixdata[x, y] = (255, 255, 255) if y>0: if pixdata[x, y-1][0] > 120 or pixdata[x, y-1][1] > 136 or pixdata[x, y-1][2] > 120: pixdata[x,y] = (255,255,255) #????? for y in range(img.size[1]): # ???????????R=95?G=95?B=95 for x in range(img.size[0]): if pixdata[x, y][0] < 160 and pixdata[x, y][1] < 160 and pixdata[x, y][2] < 160: pixdata[x, y] = (0, 0, 0) else: pixdata[x, y] = (255, 255, 255) img.filter(ImageFilter.EDGE_ENHANCE_MORE)#????(????) img.resize(((img.size[0])*2,(img.size[1])*2),Image.BILINEAR)#Image.BILINEAR?????????????? img.save(savepath)
def remove_line(giffile, savepath): (img, pixdata) = open_img(giffile) for x in range(img.size[0]): #x?? for y in range(img.size[1]): #y?? if pixdata[x, y][0] < 8 or pixdata[x, y][1] < 6 or pixdata[x, y][2] < 8 or ( pixdata[x, y][0] + pixdata[x, y][1] + pixdata[x, y][2]) <= 30: #?????? if y == 0: pixdata[x, y] = (255, 255, 255) if y > 0: if pixdata[x, y - 1][0] > 120 or pixdata[x, y - 1][1] > 136 or pixdata[x, y - 1][2] > 120: pixdata[x, y] = (255, 255, 255) #? # ????? for y in range(img.size[1]): # ???????????R=95?G=95?B=95 for x in range(img.size[0]): if pixdata[x, y][0] < 160 and pixdata[x, y][1] < 160 and pixdata[x, y][2] < 160: pixdata[x, y] = (0, 0, 0) else: pixdata[x, y] = (255, 255, 255) img.filter(ImageFilter.EDGE_ENHANCE_MORE) #????????????????????????????????????? img.resize(((img.size[0]) * 2, (img.size[1]) * 2), Image.BILINEAR) # Image.BILINEAR??????????????#? img.save(savepath+'captcha_removeline.gif') #?????????????????????dot_num?
def transformImg(self, img, t): imgT = img.transform((int(img.size[0]*t[3]),int(img.size[1]*t[3])), Image.EXTENT, (0,0,img.size[0],img.size[1]), Image.BILINEAR) imgT = imgT.rotate(numpy.rad2deg(t[0]), Image.BILINEAR, expand=1) if t[4] == 1.: imgT = imgT.transpose(Image.FLIP_LEFT_RIGHT) # crop only valid part if self.crop: imgT = imgT.crop(self.getInscribedRectangle(t[0], (img.size[0]*t[3], img.size[1]*t[3]))) # crop from translation imgT = imgT.resize((int(self.imgSize[0]*1.1), int(self.imgSize[1]*1.1)), Image.BILINEAR) xstart = int((imgT.size[0] // 2 - t[1]) - self.imgSize[0] // 2) ystart = int((imgT.size[1] // 2 - t[2]) - self.imgSize[1] // 2) assert xstart >= 0 and ystart >= 0 return imgT.crop((xstart, ystart, xstart+self.imgSize[0], ystart+self.imgSize[1]))
def transform_image(image, crop_rect, input_size, hue, sat, value, mirror): cx, cy, cw, ch = crop_rect image = image.crop((cx, cy, cx + cw, cy + ch)).resize((input_size, input_size), Image.BILINEAR) hsv_image = np.asarray(image, dtype=np.float32) dh = int((np.random.random() * 2 - 1) * hue * 255) ds = rand_scale(sat) dv = rand_scale(value) h = hsv_image[:,:,0] h += dh if dh > 0: h[h >= 256] -= 256 else: h[h < 0] += 256 hsv_image[:,:,1] *= ds hsv_image[:,:,2] *= dv image = Image.fromarray(hsv_image.clip(0, 255).astype(np.uint8), 'HSV').convert('RGB') image = np.asarray(image, dtype=np.float32) / 255.0 image = image.transpose(2, 0, 1) if mirror: return image[:,:,::-1] return image
def make_request_json(self, uri, output_json): """Produces a JSON request suitable to send to CloudML Prediction API. Args: uri: The input image URI. output_json: File handle of the output json where request will be written. """ def _open_file_read_binary(uri): try: return file_io.FileIO(uri, mode='rb') except errors.InvalidArgumentError: return file_io.FileIO(uri, mode='r') with open(output_json, 'w') as outf: with _open_file_read_binary(uri) as f: image_bytes = f.read() image = Image.open(io.BytesIO(image_bytes)).convert('RGB') image = image.resize((299, 299), Image.BILINEAR) resized_image = io.BytesIO() image.save(resized_image, format='JPEG') encoded_image = base64.b64encode(resized_image.getvalue()) row = json.dumps({'key': uri, 'image_bytes': {'b64': encoded_image}}) outf.write(row) outf.write('\n')
def _process_frame84(frame): img = np.reshape(frame, [210, 160, 3]).astype(np.float32) # RGB??? # https://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale img = img[:, :, 0] * 0.299 + img[:, :, 1] * 0.587 + img[:, :, 2] * 0.114 # ??Image?????BILINEAR?? img = Image.fromarray(img) resized_screen = img.resize((84, 110), Image.BILINEAR) resized_screen = np.array(resized_screen) x_t = resized_screen[18:102, :] x_t = np.reshape(x_t, [84, 84, 1]) return x_t.astype(np.uint8) # ??????????step?reset
def _process_frame_mario(frame): img = np.reshape(frame, [224, 256, 3]).astype(np.float32) # RGB??? # https://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale img = img[:, :, 0] * 0.299 + img[:, :, 1] * 0.587 + img[:, :, 2] * 0.114 # ??Image?????BILINEAR?? img = Image.fromarray(img) resized_screen = img.resize((84, 110), Image.BILINEAR) resized_screen = np.array(resized_screen) x_t = resized_screen[18:102, :] x_t = np.reshape(x_t, [84, 84, 1]) return x_t.astype(np.uint8) # ??????????step?reset
def AffineFromRect(rect,new_size,filter=BILINEAR): ''' Create a transform from a source rectangle to a new image. This basically crops a rectangle out of the image and rescales it to the new size. @param rect: the source link.Rect. @param new_size: new size for the image. @param filter: PIL filter to use. ''' w,h = new_size x_scale = float(w)/rect.w y_scale = float(h)/rect.h x_trans = -rect.x*x_scale y_trans = -rect.y*y_scale matrix = array([[x_scale,0,x_trans],[0,y_scale,y_trans],[0,0,1]],'d') return AffineTransform(matrix,new_size,filter)
def get_image(image_path, width, height, mode): """ Read image from image_path :param image_path: Path of image :param width: Width of image :param height: Height of image :param mode: Mode of image :return: Image data """ image = Image.open(image_path) if image.size != (width, height): # HACK - Check if image is from the CELEBA dataset # Remove most pixels that aren't part of a face face_width = face_height = 108 j = (image.size[0] - face_width) // 2 i = (image.size[1] - face_height) // 2 image = image.crop([j, i, j + face_width, i + face_height]) image = image.resize([width, height], Image.BILINEAR) return np.array(image.convert(mode))
def _screenshot_minicap(self): phone_tmp_file = '/data/local/tmp/_atx_screen-{}.jpg'.format(self._randid) local_tmp_file = self._mktemp() command = 'LD_LIBRARY_PATH=/data/local/tmp /data/local/tmp/minicap -P {} -s > {}'.format( self._minicap_params(), phone_tmp_file) try: self.adb_shell(command) self.adb_cmd(['pull', phone_tmp_file, local_tmp_file]) image = imutils.open_as_pillow(local_tmp_file) # Fix rotation not rotate right. (width, height) = image.size if self.screen_rotation in [1, 3] and width < height: image = image.rotate(90, Image.BILINEAR, expand=True) return image except IOError: raise IOError("Screenshot use minicap failed.") finally: self.adb_shell(['rm', phone_tmp_file]) base.remove_force(local_tmp_file)
def _screenshot_minicap(self): phone_tmp_file = '/data/local/tmp/_atx_screen-{}.jpg'.format(self._randid) local_tmp_file = tempfile.mktemp(prefix='atx-tmp-', suffix='.jpg') command = 'LD_LIBRARY_PATH=/data/local/tmp /data/local/tmp/minicap -P {} -s > {}'.format( self._minicap_params(), phone_tmp_file) try: self.adb_shell(command) self.adb_cmd(['pull', phone_tmp_file, local_tmp_file]) image = imutils.open_as_pillow(local_tmp_file) # Fix rotation not rotate right. (width, height) = image.size if self.screen_rotation in [1, 3] and width < height: image = image.rotate(90, Image.BILINEAR, expand=True) return image except IOError: raise IOError("Screenshot use minicap failed.") finally: if os.path.exists(local_tmp_file): os.unlink(local_tmp_file) self.adb_shell(['rm', phone_tmp_file])
def preprocess_image_crop(image_path, img_size): ''' Preprocess the image scaling it so that its smaller size is img_size. The larger size is then cropped in order to produce a square image. ''' img = load_img(image_path) scale = float(img_size) / min(img.size) new_size = (int(np.ceil(scale * img.size[0])), int(np.ceil(scale * img.size[1]))) # print('old size: %s,new size: %s' %(str(img.size), str(new_size))) img = img.resize(new_size, resample=Image.BILINEAR) img = img_to_array(img) crop_h = img.shape[0] - img_size crop_v = img.shape[1] - img_size img = img[crop_h:img_size+crop_h, crop_v:img_size+crop_v, :] img = np.expand_dims(img, axis=0) img = vgg16.preprocess_input(img) return img # util function to open, resize and format pictures into appropriate tensors
def preprocess_image_scale(image_path, img_size=None): ''' Preprocess the image scaling it so that its larger size is max_size. This function preserves aspect ratio. ''' img = load_img(image_path) if img_size: scale = float(img_size) / max(img.size) new_size = (int(np.ceil(scale * img.size[0])), int(np.ceil(scale * img.size[1]))) img = img.resize(new_size, resample=Image.BILINEAR) img = img_to_array(img) img = np.expand_dims(img, axis=0) img = vgg16.preprocess_input(img) return img # util function to convert a tensor into a valid image
def updateScreen(self, canvas): """ update the image with a new canvas""" w = canvas.width h = canvas.height img = Image.new('RGB', (w, h)) drw = ImageDraw.Draw(img) for x in xrange(w): for y in xrange(h): col = canvas.getPixel(x, y) drw.point((x,y), fill=(int(col[0]*255), int(col[1]*255), int(col[2]*255))) scl = img.resize( (87, 324), resample=Image.BILINEAR ) self.lampSrc.paste(scl, (55,227)) self.lampImg = ImageTk.PhotoImage(self.lampSrc) self.backgroundLabel.config(image=self.lampImg)
def get_random_shuffle(self, batch_size): imgarray = np.empty([batch_size, 240, 320, 3],dtype=np.float32) labelarray = np.empty([batch_size, 240, 320],dtype=np.float32) for x in range(0,batch_size): rand_i = randint(1,self.dataset_size-5) img = Image.open(self.rgb_names[rand_i]).resize((320,240),Image.BILINEAR) labelImg = Image.open(self.label_names[rand_i]).resize((320,240),Image.NEAREST) imgarray[x] = np.asarray(img) labelarray[x] = np.asarray(labelImg) return imgarray,labelarray #SUNRGBD_dataset = dataset("SUNRGBD","/media/ankur/nnseg/sunrgbd_training.txt") #img, label = SUNRGBD_dataset.get_random_shuffle(4) #Image.fromarray(np.uint8(img[1]),'RGB').show() #label = np.reshape(label,[-1]) #print(label.shape)
def write(self, buf): img = Image.frombytes('RGB', (64, 64), buf) img = img.resize((16, 16), Image.BILINEAR) for x in range(16): for y in range(16): r, g, b = img.getpixel((x, y)) self.hat.set_pixel(x, y, r, g, b) self.hat.show()
def _read_image_as_array(path, dtype, load_size, crop_size, flip): f = Image.open(path) A, B = numpy.array_split(numpy.asarray(f), 2, axis=1) if hasattr(f, 'close'): f.close() A = _resize(A, load_size, Image.BILINEAR, dtype) B = _resize(B, load_size, Image.NEAREST, dtype) sx, sy = numpy.random.randint(0, load_size-crop_size, 2) A = _crop(A, sx, sy, crop_size) B = _crop(B, sx, sy, crop_size) if flip and numpy.random.rand() > 0.5: A = numpy.fliplr(A) B = numpy.fliplr(B) return A.transpose(2, 0, 1), B.transpose(2, 0, 1)
def __init__(self, dataDir='./facade/base', data_range=(1,300)): print("load dataset start") print(" from: %s"%dataDir) print(" range: [%d, %d)"%(data_range[0], data_range[1])) self.dataDir = dataDir self.dataset = [] for i in range(data_range[0],data_range[1]): img = Image.open(dataDir+"/cmp_b%04d.jpg"%i) label = Image.open(dataDir+"/cmp_b%04d.png"%i) w,h = img.size r = 286/min(w,h) # resize images so that min(w, h) == 286 img = img.resize((int(r*w), int(r*h)), Image.BILINEAR) label = label.resize((int(r*w), int(r*h)), Image.NEAREST) img = np.asarray(img).astype("f").transpose(2,0,1)/128.0-1.0 label_ = np.asarray(label)-1 # [0, 12) label = np.zeros((12, img.shape[1], img.shape[2])).astype("i") for j in range(12): label[j,:] = label_==j self.dataset.append((img,label)) print("load dataset done")
def __init__(self, dataDir='./facade/base', data_range=(1, 300)): print("load dataset start") print(" from: %s" % dataDir) print(" range: [%d, %d)" % (data_range[0], data_range[1])) self.dataDir = dataDir self.dataset = [] for i in range(data_range[0], data_range[1]): img = Image.open(dataDir + "/cmp_b%04d.jpg" % i) label = Image.open(dataDir + "/cmp_b%04d.png" % i) w, h = img.size r = 286 / min(w, h) # resize images so that min(w, h) == 286 img = img.resize((int(r * w), int(r * h)), Image.BILINEAR) label = label.resize((int(r * w), int(r * h)), Image.NEAREST) img = numpy.asarray(img).astype("f").transpose(2, 0, 1) / 128.0 - 1.0 label_ = numpy.asarray(label) - 1 # [0, 12) label = numpy.zeros((12, img.shape[1], img.shape[2])).astype("i") for j in range(12): label[j, :] = label_ == j self.dataset.append((img, label)) print("load dataset done")
def generate(): global model, opt, transformers if 'img' in request.form: img_data = re.sub('^data:image/.+;base64,', '', request.form['img']) img_data = base64.b64decode(img_data) img = Image.open(BytesIO(img_data)).convert('RGB') img = img.resize((256, 256), Image.BILINEAR) img = convert_image(img, model, transformers) return jsonify({'img': serve_pil_image(img).decode('utf-8')}) elif 'img' in request.json: img_data = re.sub('^data:image/.+;base64,', '', request.json['img']) img_data = base64.b64decode(img_data) img = Image.open(BytesIO(img_data)).convert('RGB') img = img.resize((256, 256), Image.BILINEAR) img = convert_image(img, model, transformers) return jsonify({'img': serve_pil_image(img).decode('utf-8')}) return jsonify({'error': 'img not found'})
def resize(self, size, filter=Image.BILINEAR): new_data = [] for fname, im, meta in self.data: if self.get_data_type() == "image": new_data.append((fname, im.resize(size, filter), meta)) elif self.get_data_type() == "array": zx = size[0] / im.shape[1] zy = size[1] / im.shape[2] r = scipy.ndimage.interpolation.zoom(im[0,:,:], [zx,zy]) g = scipy.ndimage.interpolation.zoom(im[1,:,:], [zx,zy]) b = scipy.ndimage.interpolation.zoom(im[2,:,:], [zx,zy]) new_data.append((fname, numpy.concatenate((r[None,:,:],g[None,:,:],b[None,:,:]), axis=0), meta)) self.data = new_data #
def make_request_json(self, uri, output_json): """Produces a JSON request suitable to send to CloudML Prediction API. Args: uri: The input image URI. output_json: File handle of the output json where request will be written. """ with open(output_json, 'w') as outf: with file_io.FileIO(uri, mode='rb') as f: image_bytes = f.read() image = Image.open(io.BytesIO(image_bytes)).convert('RGB') image = image.resize((299, 299), Image.BILINEAR) resized_image = io.BytesIO() image.save(resized_image, format='JPEG') encoded_image = base64.b64encode(resized_image.getvalue()) row = json.dumps({'key': uri, 'image_bytes': {'b64': encoded_image}}) outf.write(row) outf.write('\n')
def produceImage(filename,platform): print 'Processing:' + filename img = Image.open(filename) index = 0 sizes = sizesiOS folders = foldersiOS if platform == 'android':#??ios?????? sizes = sizesAndroid folders = foldersAndroid for size in sizes: if not os.path.isdir(folders[index]): os.mkdir(folders[index]) if img.size[0] > img.size[1]:#?????????? im = img.resize((size[1],size[0]),Image.BILINEAR) im.save(folders[index]+'/'+filename) else: im = img.resize(size,Image.BILINEAR) im.save(folders[index]+'/'+filename) index = index + 1
def main(): if len(sys.argv) != 4: print 'Wrong number of inputs' return image_dir = sys.argv[2] output_dir = sys.argv[3] dim = int(sys.argv[1]) out_size = (dim, dim) filenames = [x for x in os.listdir(image_dir) if not x.startswith('.')] for image_name in filenames: filename = os.path.join(image_dir, image_name) img = Image.open(filename) # img.thumbnail(out_size, Image.ANTIALIAS) img = img.resize(out_size, Image.BILINEAR) out_file = os.path.join(output_dir, image_name) img.save(out_file, "JPEG")
def asratio_resize(im, outw, outh): imw = im.size[0] imh = im.size[1] result=np.zeros((outw*outh*3)).reshape(outw,outh,3) if (outw/imw > outh/imh): ratio = outh/imh imr = im.resize((imw*ratio, outh), Image.BILINEAR ) w, h = imr.size offset = (outw - w)/2 result[:,offset:offset+w] = np.asarray(imr) else: ratio = outw/imw imr = im.resize((outw, imh*ratio), Image.BILINEAR ) w, h = imr.size offset = (outh - h)/2 result[offset:offset+w] = np.asarray(imr) return result # img value is 0~255
def _quilt(self, avatars): """ Makes a quilt of avatars of avatars that tries to be as square as possible """ xbound = math.ceil(math.sqrt(len(avatars))) ybound = math.ceil(len(avatars) / xbound) size = int(2520 / xbound) base = Image.new(mode='RGBA', size=(xbound * size, ybound * size), color=(0, 0, 0, 0)) x, y = 0, 0 for avatar in avatars: im = Image.open(avatar) base.paste(im.resize((size, size), resample=Image.BILINEAR), box=(x * size, y * size)) if x < xbound - 1: x += 1 else: x = 0 y += 1 buffer = BytesIO() base.save(buffer, 'png') buffer.seek(0) return discord.File(buffer, filename='quilt.png')
def crop_and_move(fn, ext='good'): img = Image.open(fn).convert('RGB') w, h = img.size if w < h: ow = 256 oh = int(256 * h / w) img = img.resize((ow, oh), Image.BILINEAR) else: oh = 256 ow = int(256 * w / h) img = img.resize((ow, oh), Image.BILINEAR) w, h = img.size th = 224 tw = 224 x1 = int(round((w - tw) / 2.)) y1 = int(round((h - th) / 2.)) img = img.crop((x1, y1, x1 + tw, y1 + th)) img.save(ext+ '/' + fn.split('/')[-1].split('.')[0] + '.jpg')
def __call__(self, images): single = False if not isinstance(images, collections.Sequence): images = [images] single = True interps = self.interpolations if interps == 'auto': interps = Image.BILINEAR if len(images) == 2: interps = [Image.BILINEAR, Image.NEAREST] if not isinstance(interps, collections.Sequence): interps = [interps] * len(images) resized = [] ratio = random.uniform(self.low, self.high) for img, interp in zip(images, interps): h, w = img.size[0], img.size[1] h2, w2 = (int(ratio * h), int(ratio * w)) img2 = img.resize((h2, w2), interp) resized.append(img2) if single: resized = resized[0] return resized
def __call__(self, img): # standardize image size w, h = 178, 218 # standard image size if img.size != (w, h): img.resize((w, h), Image.BILINEAR) # crop face x1 = int(round((w - self.crop_size) / 2.0)) y1 = int(round((h - self.crop_size) / 2.0) + self.y_offset) img = img.crop((x1, y1, x1 + self.crop_size, y1 + self.crop_size)) # post transform img = self.post_transform(img) return img
def process_photo_thread(): while True: task = photo_queue.get() if task is None: break dst_photo_filename = task['src_filename'] if type(max_photo_size) is int: im = Image.open(task['src_filename']) if im.width > max_photo_size or im.height > max_photo_size: im.thumbnail((max_photo_size, max_photo_size), Image.BILINEAR) handle, dst_photo_filename = mkstemp(prefix='smarthomebot-', suffix='.jpg') if verbose: print('Resizing photo to {} ...'.format(dst_photo_filename)) im.save(dst_photo_filename, format='JPEG', quality=87) os.remove(task['src_filename']) im.close() if verbose: print('Sending photo {} ...'.format(dst_photo_filename)) for user in authorized_users: bot.sendPhoto(user, open(dst_photo_filename, 'rb'), caption=datetime.datetime.now().strftime('%d.%m.%Y %H:%M:%S')) os.remove(dst_photo_filename)
def __init__(self, size, interpolation=Image.BILINEAR): self.size = size self.interpolation = interpolation self.toTensor = transforms.ToTensor()
def __call__(self, img, mask): assert img.size == mask.size return img.resize(self.size, Image.BILINEAR), mask.resize(self.size, Image.NEAREST)
def __call__(self, img, mask): assert img.size == mask.size w, h = img.size if (w >= h and w == self.size) or (h >= w and h == self.size): return img, mask if w > h: ow = self.size oh = int(self.size * h / w) return img.resize((ow, oh), Image.BILINEAR), mask.resize((ow, oh), Image.NEAREST) else: oh = self.size ow = int(self.size * w / h) return img.resize((ow, oh), Image.BILINEAR), mask.resize((ow, oh), Image.NEAREST)
def __call__(self, img, mask): assert img.size == mask.size for attempt in range(10): area = img.size[0] * img.size[1] target_area = random.uniform(0.45, 1.0) * area aspect_ratio = random.uniform(0.5, 2) w = int(round(math.sqrt(target_area * aspect_ratio))) h = int(round(math.sqrt(target_area / aspect_ratio))) if random.random() < 0.5: w, h = h, w if w <= img.size[0] and h <= img.size[1]: x1 = random.randint(0, img.size[0] - w) y1 = random.randint(0, img.size[1] - h) img = img.crop((x1, y1, x1 + w, y1 + h)) mask = mask.crop((x1, y1, x1 + w, y1 + h)) assert (img.size == (w, h)) return img.resize((self.size, self.size), Image.BILINEAR), mask.resize((self.size, self.size), Image.NEAREST) # Fallback scale = Scale(self.size) crop = CenterCrop(self.size) return crop(*scale(img, mask))
def __call__(self, img, mask): rotate_degree = random.random() * 2 * self.degree - self.degree return img.rotate(rotate_degree, Image.BILINEAR), mask.rotate(rotate_degree, Image.NEAREST)
def __init__(self, size, interpolation=Image.BILINEAR): self.size = size self.interpolation = interpolation
def load_image(self, img_path): self.test_img_path = img_path image_pr = Image.open(img_path) image = self.image2pixelarray(image_pr.resize((80, 80), Image.BILINEAR)) return image, image_pr
def captcha_draw(label, fonts, dir_path, pic_id): # width, height = 512, 48 # size_cha = random.randint(24, 48) # ???? # derx = random.randint(0, 16) # im = Image.new(mode='L', size=(width, height), color='white') # color ?????size ???? # drawer = ImageDraw.Draw(im) # font = ImageFont.truetype(random.choice(fonts), size_cha) # drawer.text(xy=(derx, 0), text=label, font=font, fill='black') #text ???font ???????? # # im.show() # write2file(dir_path, label, im) width, height = 32, 32 size_cha = random.randint(16, 28) # ???? derx = random.randint(0, max(width-size_cha-10, 0)) dery = random.randint(0, max(height-size_cha-10, 0)) im = Image.new(mode='L', size=(width, height), color='white') # color ?????size ???? drawer = ImageDraw.Draw(im) font = ImageFont.truetype(random.choice(fonts), size_cha) drawer.text(xy=(derx, dery), text=label, font=font, fill='black') #text ???font ???????? # if label != ' ' and (img_as_float(im) == np.ones((48, 48))).all(): # # in case the label is not in this font, then the image will be all white # return 0 im = im.convert('RGBA') max_angle = 45 # to be tuned angle = random.randint(-max_angle, max_angle) im = im.rotate(angle, Image.BILINEAR, expand=0) fff = Image.new('RGBA', im.size, (255,)*4) im = Image.composite(im, fff, im) # if random.random() < 0.5: # im = Image.fromarray(grey_erosion(im, size=(2, 2))) # erosion # if random.random() < 0.5: # im = Image.fromarray((random_noise(img_as_float(im), mode='s&p')*255).astype(np.uint8)) # im = im.filter(ImageFilter.GaussianBlur(radius=random.random())) # im.show() write2file(dir_path, label, im, pic_id) return 1
def resizeToOutput(self, image, coef, h_pad, w_pad): image = image.resize((int(self.original_W/coef), int(self.original_H/coef)), resample=Image.BILINEAR) outputImage = Image.new("RGB",(self.output_W,self.output_H),(0,0,0)) outputImage.paste(image,(w_pad,h_pad)) return outputImage
def make_request_json(input_images, output_json, do_resize): """Produces a JSON request suitable to send to CloudML Prediction API. Args: input_images: List of file handles corresponding to images to be encoded. output_json: File handle of the output json where request will be written. do_resize: Boolean specifying if script should resize images. """ with open(output_json, 'w') as ff: for image_handle in input_images: # Uses argparse to check permissions, but ignore pre-opened file handle. image = Image.open(image_handle.name) image_handle.close() resized_handle = StringIO() is_too_big = ((image.size[0] * image.size[1]) > (desired_width * desired_height)) if do_resize and is_too_big: image = image.resize((299, 299), Image.BILINEAR) image.save(resized_handle, format='JPEG') encoded_contents = base64.b64encode(resized_handle.getvalue()) # key can be any UTF-8 string, since it goes in a HTTP request. row = json.dumps({'key': image_handle.name, 'image_bytes': {'b64': encoded_contents}}) ff.write(row) ff.write('\n') print 'Wrote {} images to {}'.format(len(input_images), output_json)
def AffineTranslate(dx,dy,new_size,filter=BILINEAR): ''' Create a simple translation transform @param dx: translation in the x direction @param dy: translation in the y direction @param new_size: new size for the image @param filter: PIL filter to use ''' matrix = array([[1,0,dx],[0,1,dy],[0,0,1]],'d') return AffineTransform(matrix,new_size,filter)