Python PIL.Image 模块,new() 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用PIL.Image.new()。
def _normalize(self):
# costumes
if self.costume:
# Make sure it's in costumes
if self.costume not in self.costumes:
self.costumes.append(self.costume)
else:
# No costume!
if self.costumes:
self.costume = self.costumes[0]
else:
BLACK = (0, 0, 0)
self.costume = Costume("blank", Image.new((1, 1), BLACK))
self.costumes = [self.costume]
# scripts
for script in self.scripts:
script._normalize()
# sort scripts by y position
have_position = [s for s in self.scripts if s.pos]
no_position = [s for s in self.scripts if not s.pos]
have_position.sort(key=lambda s: (s.pos[1], s.pos[0]))
self.scripts = have_position + no_position
def generate_img(output="", theme={}, text="", resolution=(1920,1080)):
# img = Image.open(backdrop)
img = Image.new("RGB", resolution, theme["background"])
W, H = img.size
logo = Image.open(DEFAULT_DIR+"/assets/logo.png")
colorized_img = ImageOps.colorize(logo.convert("L"), theme["text"], theme["background"])
size = int((W/100)*17)
logo_newsize = colorized_img.resize((size, size), Image.ANTIALIAS)
img.paste(logo_newsize, (int((W-size)/2), int((H-size)/2)))
draw = ImageDraw.Draw(img)
base_font_pixle = int((56/1920)*resolution[0])
font = ImageFont.truetype("DejaVuSansMono.ttf", base_font_pixle)
w, h = font.getsize(text)
text_draw(draw, text, base_font_pixle, img.size, theme)
img.save(output, quality=100)
def makeglyphs():
for i in range(0, len(C)):
im = Image.new("RGB", (100, 110))
dr = ImageDraw.Draw(im)
font = ImageFont.truetype(os.path.join(os.path.dirname(__file__),"fonts/Impact.ttf"), 124)
dr.text((0, -25), C[i], (255, 255, 255), font=font)
fwx = firstwhitex(im)
im = Image.new("RGB", 124)
dr.text((-fwx, -26), font=font)
cimgs.append(im)
# make threshold image
def MakeBayer(matrixSize, savePng, pngTileCount):
pngFilename = 'bayer%d.png' % matrixSize
if (pngTileCount > 1):
pngFilename = 'bayer%dtile%d.png' % (matrixSize, pngTileCount)
matrix = InitBayer(0, matrixSize, 1)
if (savePng):
from PIL import Image
brightnessMultiplier = {16:1,8:4,4:16,2:64}
img = Image.new('RGB', (matrixSize*pngTileCount,
matrixSize*pngTileCount))
imgData = img.load()
for y in range(img.height):
for x in range(img.width):
value = matrix[y % matrixSize][x % matrixSize]
value *= brightnessMultiplier[matrixSize]
color = (value, value, value)
imgData[x,y] = color
img.save(pngFilename, "PNG")
print('Saved %s' % pngFilename)
else:
print('Bayer Matrix %s' % matrixSize)
print(matrix)
def draw2d(data,labels,jpeg='mds2d.jpg'):
img=Image.new('RGB',(2000,2000),(255,255,255))
draw=ImageDraw.Draw(img)
for i in range(len(data)):
x=(data[i][0]+0.5)*1000
y=(data[i][1]+0.5)*1000
draw.text((x,y),labels[i],(0,0,0))
img.save(jpeg,'JPEG')
def __fixup(self, im1):
# convert image to suitable mode
if isinstance(im1, _Operand):
# argument was an image.
if im1.im.mode in ("1", "L"):
return im1.im.convert("I")
elif im1.im.mode in ("I", "F"):
return im1.im
else:
raise ValueError("unsupported mode: %s" % im1.im.mode)
else:
# argument was a constant
if _isconstant(im1) and self.im.mode in ("1", "L", "I"):
return Image.new("I", self.im.size, im1)
else:
return Image.new("F", im1)
def __init__(self, master, foreground="black", truetype_font=None, font_path=None, family=None, size=None, **kwargs):
if truetype_font is None:
if font_path is None:
raise ValueError("Font path can't be None")
# Initialize font
truetype_font = ImageFont.truetype(font_path, size)
width, height = truetype_font.getsize(text)
image = Image.new("RGBA", (width, height), color=(0,0))
draw = ImageDraw.Draw(image)
draw.text((0, 0), font=truetype_font, fill=foreground)
self._photoimage = ImageTk.PhotoImage(image)
Label.__init__(self, image=self._photoimage, **kwargs)
def create_thumb_js(self, mode=None, pth=None):
""" Create the thumbnail using SmartCrop.js """
if pth is None:
raise ValueError("path can't be None")
# save a copy of the image with the correct orientation in a temporary
# file
_, tmpfname = tempfile.mkstemp(suffix='.'+settings.output_format)
self.original_image.save(tmpfname, quality=95)
# Load smartcrop and set options
nwidth, nheight = self.resize_dims(mode)
logging.info("[%s] SmartCrop.js new dimensions: %ix%i" % (self.name,
nwidth, nheight))
command = [settings.smartcrop_js_path, '--width', str(nwidth),
'--height', str(nheight), tmpfname, pth]
logging.info("[%s] SmartCrop.js running crop command." % self.name)
check_output(command)
# remove the temporary file
os.remove(tmpfname)
return pth
def createIconGD(file, size=100, raw=True):
"""
Implements the actual logic behind creating the icon/thumbnail
:type file: str
:param file: path to the file name
:rtype: image
:return: icon/thumbnail for the video
"""
image = Image.open(file)
width, height = image.size
if width > height:
y = 0
x = (width - height) / 2
smallestSide = height
else:
x = 0
y = (height - width) / 2
smallestSide = width
# image_p = Image.new('RGB',(size,size))
# image = Image.frombytes('RGBa',size),file_get_contents(file))
image.thumbnail((size, size))
##todo convert to jpeg
i = image.tobytes()
image.close()
# image_p.close()
return i
def image_to_pdf(self, img, pdf_path=None, **kwargs):
"""
Convert image to pdf.
:param img: image file opened by PIL
:param pdf_path: path to save pdf
:param kwargs: any parameter accepted by Image.save i.e. quality
:return:
"""
processor = ResizetoFit(width=self.max_size_in_pixels[0], height=self.max_size_in_pixels[1])
img = processor.process(img)
# Create a white canvas and paste the image
final_img_width = min(img.size[0], self.max_size_in_pixels[0])
final_img_height = min(img.size[1], self.max_size_in_pixels[1])
tmp_image = Image.new("RGB", (final_img_width, final_img_height), "white")
margin_left = 0
margin_top = 0
tmp_image.paste(img, (margin_left, margin_top,
final_img_width, final_img_height))
# Save the image as .pdf file
if not pdf_path:
f = NamedTemporaryFile(delete=False)
pdf_path = f.name
tmp_image.save(pdf_path, "PDF", resolution=100.0, **kwargs)
return pdf_path
def drawChars(charset, font, char_size):
src_font = ImageFont.truetype(font, 150)
canvas = Image.new("RGB", (char_size*21, char_size*19), 255)) # 42 -> 21
x_pos = 0
y_pos = 0
for c in charset:
e = draw_single_char(c, src_font, char_size, x_offset=50, y_offset=20)
canvas.paste(e, (x_pos * char_size, y_pos * char_size))
x_pos = x_pos + 1
if x_pos >= 21: # 42 -> 21
x_pos = 0
y_pos = y_pos + 1
draw = ImageDraw.Draw(canvas)
for i in range(20): # 41 -> 20
draw.line([((i+1)*char_size,0), ((i+1)*char_size, char_size*19)], fill = (0, width=5)
for i in range(18):
draw.line([(0, (i+1)*char_size), (i+1)*char_size)], width=5) # 42 -> 21
canvas.save("399_image.png")
def avatar_gen_img(self):
font_size = int(self.size / 10 * 8)
pic_size = self.size
an, is_letter = self.avatar_name()
font = self.zh_font_file_name
if is_letter:
font = self.en_font_file_name
font_size = int(self.size / 10 * 11)
font_file = os.path.abspath(os.path.join(self.font_dir, font))
pygame.init()
f = pygame.font.Font(font_file, font_size)
is_light=self.is_light_color(self.avatar_background_color())
rtext = f.render(an.upper(), True, (0,0) if is_light else (255, 255))
# pygame.image.save(rtext,'%s.png' % an)
mode = 'RGBA'
astr = pygame.image.tostring(rtext, 'RGBA')
circle = Image.new("RGBA", (self.size, self.size))
word = Image.frombytes(mode, f.size(an), astr)
word_x = int((pic_size - word.size[0]) / 2)
word_y = int(word_x * 0.9)
if is_letter:
word_y = int((pic_size - word.size[1]) / 2)
draw = ImageDraw.Draw(circle)
draw.ellipse((0, self.size , self.size ),
fill=self.avatar_background_color(), outline=self.avatar_background_color())
draw.point((100, 100), 'red')
r, g, b, a = word.split()
circle.paste(word, (word_x, word_y), a)
sharpness = ImageEnhance.Sharpness(circle)
# circle = sharpness.enhance(7.0)
# im.show()
# circle.show()
# print(circle)
return circle
def test_crop(self):
"""Test UPLOADER crop works."""
u = Uploader()
size = (100, 100)
im = Image.new('RGB', size)
folder = tempfile.mkdtemp()
u.upload_folder = folder
im.save(os.path.join(folder, 'image.png'))
coordinates = (0, 50, 50)
file = FileStorage(filename=os.path.join(folder, 'image.png'))
with patch('pybossa.uploader.Image', return_value=True):
err_msg = "It should crop the image"
assert u.crop(file, coordinates) is True, err_msg
with patch('pybossa.uploader.Image.open', side_effect=IOError):
err_msg = "It should return false"
assert u.crop(file, coordinates) is False, err_msg
def read_image(filename):
f = open(filename, 'rb')
index = 0
buf = f.read()
f.close()
magic, images, rows, columns = struct.unpack_from('>IIII' , buf , index)
index += struct.calcsize('>IIII')
for i in xrange(images):
#for i in xrange(2000):
image = Image.new('L', (columns, rows))
for x in xrange(rows):
for y in xrange(columns):
image.putpixel((y, x), int(struct.unpack_from('>B', buf, index)[0]))
index += struct.calcsize('>B')
print 'save ' + str(i) + 'image'
image.save('./test/' + str(i) + '.png')
def new_image(self, **kwargs):
back_color = kwargs.get("fill_color", "white")
fill_color = kwargs.get("back_color", "black")
if fill_color.lower() != "black" or back_color.lower() != "white":
if back_color.lower() == "transparent":
mode = "RGBA"
back_color = None
else:
mode = "RGB"
else:
mode = "1"
img = Image.new(mode, (self.pixel_size, self.pixel_size), back_color)
self.fill_color = fill_color
self._idr = ImageDraw.Draw(img)
return img
def whitespace(image, size, whitespace=False, whitespace_color=None, **kwargs):
if not whitespace:
return image
if whitespace_color is None:
whitespace_color = FILER_WHITESPACE_COLOR
if whitespace_color is None:
whitespace_color = '#fff'
old_image = image
source_x, source_y = image.size
target_x, target_y = size
image = Image.new('RGBA', (target_x, target_y), whitespace_color)
if source_x < target_x and source_y < target_y: # whitespace all around
image.paste(old_image, (
(target_x - source_x) / 2, (target_y - source_y) / 2))
elif source_x < target_x: # whitespace on top and bottom only
image.paste(old_image, ((target_x - source_x) / 2, 0))
elif source_y < target_y: # whitespace on sides only
image.paste(old_image, (target_y - source_y) / 2))
else: # no whitespace needed
image = old_image
return image
def decode_labels(mask):
"""Decode batch of segmentation masks.
Args:
label_batch: result of inference after taking argmax.
Returns:
An batch of RGB images of the same size
"""
img = Image.new('RGB', (len(mask[0]), len(mask)))
pixels = img.load()
for j_, j in enumerate(mask):
for k_, k in enumerate(j):
if k < 21:
pixels[k_,j_] = label_colours[k]
return np.array(img)
def thres(pil_Image):
""" Thresholding the image
"""
w, h = pil_Image.size
thim = Image.new("RGB", (w, h))
thdr = ImageDraw.Draw(thim)
PX = pil_Image.load()
# make threshold image
for x in range(0, w):
for y in range(0, h):
r, b = PX[x, y][:3]
hsv = rgb2hsv(r, b)
if hsv[2] > 0.9 and hsv[1] < 0.1:
thdr.point([x, y], fill=(0, 0))
else:
thdr.point([x, fill=(255, 255))
thim.show()
return thim
def demo(drm, start):
"""simple partial update demo - draw random shapes"""
# Use a monochrome image to force 0/1 values
image = Image.new('1', drm.image.size)
# prepare for drawing
draw = ImageDraw.Draw(image)
width, height = drm.image.size
font = ImageFont.truetype(FONT_FILE, FONT_SIZE)
counter = start & 0xffff
while True:
draw.rectangle((0, width, fill='black', outline='black')
draw.text((0, '{c:04X}'.format(c=counter), fill='white', font=font)
counter = (counter + 1) & 0xffff
# display image on the panel
image.convert('RGBX')
drm.image.paste(image)
drm.flush()
# main
def shred(self,args):
image_path = args.path
shredS = 250
image = Image.open(image_path)
# shredded = Image.new("1",image.size)
width, height = image.size
shred_width = width // shredS
size = shred_width * shredS
shredded = Image.new("RGB", (size, height))
sequence = list(range(0, shredS))
shuffle(sequence)
for i, shred_index in enumerate(sequence):
shred_x1, shred_y1 = shred_width * shred_index, 0
shred_x2, shred_y2 = shred_x1 + shred_width, height
region = image.crop((shred_x1, shred_y1, shred_x2, shred_y2))
shredded.paste(region, (shred_width * i, 0))
shredded.save(image_path)
def make_image(text, fontsize=45, output_file='tmp.png', fontname='HamletorNot.ttf'):
"""Make an image out of a poem"""
# Get font
font = ImageFont.truetype(fontname, fontsize * factor)
# Compute height
num_lines = (1 + text.strip().count('\n'))
height = num_lines * font.getsize(text[:10])[1] / factor + 2 * pad
# Compute width
font_length = max(font.getsize(line)[0] for line in text.split('\n'))
width = font_length / factor + 2 * pad
# Create big image and draw text
image = Image.new("RGBA", (width * factor, height * factor), (241, 241, 212))
draw = ImageDraw.Draw(image)
draw.text((pad * factor, pad * factor), font=font)
# Resize with antialiasing
img_resized = image.resize((width, Image.ANTIALIAS)
# Save to file
img_resized.save(output_file)
def convert(self, *formats):
"""Return an Image instance with the first matching format.
For each format in ``*args``: If the image's :attr:`format` attribute
is the same as the format,return self,otherwise try the next format.
If none of the formats match,return a new Image instance with the
last format.
"""
for format in formats:
format = Image.image_format(format)
if self.format == format:
return self
else:
return self._convert(format)
def mandelbrot_calc_set(w, h, max_iteration=10000, output='mandelbrot_mp.png'):
""" Calculate a mandelbrot set given the width,height and
maximum number of iterations """
image = Image.new("RGB", h))
image_rows = pymp.shared.dict()
with pymp.Parallel(4) as p:
for y in p.range(0, h):
mandelbrot_calc_row(y, w, image_rows, max_iteration)
for i in range(w*h):
x,y = i % w, i // w
image.putpixel((x, image_rows[i])
image.save(output, "PNG")
print('Saved to',output)
def mandelbrot_main(w, max_iterations=1000, output='mandelbrot_celery.png'):
""" Main function for mandelbrot program with celery """
job = group([mandelbrot_calc_row.s(y, max_iterations) for y in range(h)])
result = job.apply_async()
image = Image.new('RGB', h))
for image_rows in result.join():
for k,v in image_rows.items():
k = int(k)
v = tuple(map(int, v))
x,y = k % args.width, k // args.width
image.putpixel((x, v)
image.save(output, 'PNG')
print('Saved to',output)
def mandelbrot_calc_set(w,output)
def drawSimpleSegment(self):
#Drawing module
im_Width, im_Height = self.pred_size
prediction_image = Image.new("RGB", (im_Width, im_Height) ,0))
prediction_imageDraw = ImageDraw.Draw(prediction_image)
#BASE all image segmentation
for i in range(im_Width):
for j in range(im_Height):
#get matrix element class(0-149)
px_Class = self.predicted_classes[j][i]
#assign color from .mat list
put_Px_Color = tuple(self.class_colors['colors'][px_Class])
#drawing
prediction_imageDraw.point((i,j), fill=put_Px_Color)
#Resize to original size and save
self.coef, self.h_pad, self.w_pad = self.calculateResize()
FullHdOutimage = self.resizetoOutput(prediction_image, self.coef, self.w_pad)
FullHdOutimage = Image.blend(FullHdOutimage, self.im, 0.5)
return FullHdOutimage
def make_book(name,dir):
orig = name
if len(name)<2:
name += name
left = Image.open('./resources/left.png').convert('RGBA')
right = Image.open('./resources/right.png').convert('RGBA')
face = Image.open('./resources/face.png').convert('RGBA')
left = ImageChops.multiply(left, Image.new('HSV', left.size, makeLetterTint(name[0])).convert('RGBA'))
right = ImageChops.multiply(right, right.size, makeLetterTint(name[1])).convert('RGBA'))
left.paste(right,right)
left.paste(face,face)
left.save('{}/{}.png'.format(dir,orig))
def main():
global should_draw
start = time.time()
print('Gathering Data')
path, prompt, scores, Votes, twowers, twower_count, top_number, elim_number = parse_args()
print('Processing scores')
scores = process_Votes(Votes, path)
if should_draw:
print('Drawing Image')
base = Image.new('RGBA',(1368,1368),color=(255,255))
drawer = ImageDraw.Draw(base)
prompt, base, drawer, header_height = draw_header(prompt,scores)
scores = draw_rankings(scores,top_number,elim_number,twower_count,base,drawer,header_height,twowers)
base.save('./twows/{}/results.png'.format(path))
print('Recording Data')
write_csv(scores,path)
write_history(path)
end = time.time()
print('Time taken {} seconds'.format(end-start))
def displayImageFileOnLCD(filename):
print 'displays ', filename
title = 'Review Mode'
# resize/dither to screen resolution and send to LCD
image = Image.open(filename)
im_width, im_height = image.size
if im_width < im_height:
image = image.rotate(90)
image.thumbnail(S_SIZE, Image.ANTIALIAS)
image_sized = Image.new('RGB', S_SIZE, 0))
image_sized.paste(image,((S_SIZE[0] - image.size[0]) / 2, (S_SIZE[1] - image.size[1]) / 2))
# draw filename
draw = ImageDraw.Draw(image_sized)
font = ImageFont.truetype('arial.ttf', 18)
draw.rectangle([(0, (115, 22)],255), outline=(0,0))
draw.text((2, 2), title, font=font)
draw.rectangle([(279, 217), (399, 239)],0))
draw.text((290, 218), filename, font=font)
# display on LCD
image_sized = ImageOps.invert(image_sized)
image_sized = image_sized.convert('1') # convert image to black and white
lcd.write(image_sized.tobytes())
def shrink_image(data, resize):
picture = requests.get(data).content
image = Image.open(StringIO(picture))
if resize == True: image = resizeimage.resize_width(image, 200)
data = list(image.getdata())
image_without_exif = Image.new(image.mode, image.size)
image_without_exif.putdata(data)
picture_number = 1
buffer = StringIO()
image_without_exif.save(buffer, format='jpeg')
return buffer.getvalue()
def apply_watermark(im, mark, position, opacity=1):
"""Adds a watermark to an image."""
if opacity < 1:
mark = reduce_opacity(mark, opacity)
if im.mode != 'RGBA':
im = im.convert('RGBA')
# create a transparent layer the size of the image and draw the
# watermark in that layer.
layer = Image.new('RGBA', im.size, 0))
if position == 'tile':
for y in range(0, im.size[1], mark.size[1]):
for x in range(0, im.size[0], mark.size[0]):
layer.paste(mark, (x, y))
elif position == 'scale':
# scale,but preserve the aspect ratio
ratio = min(
float(im.size[0]) / mark.size[0], float(im.size[1]) / mark.size[1])
w = int(mark.size[0] * ratio)
h = int(mark.size[1] * ratio)
mark = mark.resize((w, h))
layer.paste(mark, (round((im.size[0] - w) / 2), round((im.size[1] - h) / 2)))
else:
layer.paste(mark, position)
# composite the watermark with the layer
return Image.composite(layer, im, layer)
def __call__(self, value):
if isinstance(value, str) and len(value) == 0:
return (value, None)
from PIL import Image
from io import BytesIO
try:
img = Image.open(value.file)
img.thumbnail((self.nx, self.ny), Image.ANTIALIAS)
s = BytesIO()
if self.padding:
background = Image.new('RGBA', (self.nx, 0))
background.paste(
img,
((self.nx - img.size[0]) // 2, (self.ny - img.size[1]) // 2))
background.save(s, 'JPEG', quality=self.quality)
else:
img.save(s, quality=self.quality)
s.seek(0)
value.file = s
except:
return (value, self.error_message)
else:
return (value, None)
def process_zheight_change(self, payload):
if not self._printer.is_printing():
return False
if not "new" in payload:
return False
height_interval = float(self._settings.get(['supported_events'], merged=True).get('Progress').get('IntervalHeight'))
if height_interval <= 0:
return False
new = payload["new"]
if new <= self.last_trigger_height:
return False
if new >= (self.last_trigger_height + height_interval):
self._logger.debug("ZChange interval: " + str(height_interval) + ",Last trigger height: " + str(self.last_trigger_height) + ",Payload: " + json.dumps(payload))
self.last_trigger_height = new
return True
return False
def test_resized_images_updated(self):
"""
thumbnails should be updated if image is already present and updated when update_image=True
"""
assert self.profile.image
assert self.profile.image_small
assert self.profile.image_medium
# create a dummy image file in memory for upload
image_file = BytesIO()
image = Image.new('RGBA', size=(50, 50), color=(256, 0))
image.save(image_file, 'png')
image_file.seek(0)
self.profile.image = UploadedFile(image_file, "filename.png", "image/png", len(image_file.getvalue()))
self.profile.save(update_image=True)
image_file_bytes = image_file.read()
assert self.profile.image_small.file.read() != image_file_bytes
assert self.profile.image_medium.file.read() != image_file_bytes
def test_upload_image(self):
"""
An image upload should not delete education or work history entries
"""
with mute_signals(post_save):
profile = ProfileFactory.create(user=self.user1)
EducationFactory.create(profile=profile)
EmploymentFactory.create(profile=profile)
self.client.force_login(self.user1)
# create a dummy image file in memory for upload
image_file = BytesIO()
image = Image.new('RGBA', 'png')
image_file.seek(0)
# format patch using multipart upload
resp = self.client.patch(self.url1, data={
'image': image_file
}, format='multipart')
assert resp.status_code == 200, resp.content.decode('utf-8')
assert profile.education.count() == 1
assert profile.work_history.count() == 1
def convert(img_path,name):
print img_path,name
name = name.split('.')[0]
png = Image.open(img_path).convert('RGBA')
print 'creating images (%s)' % name
for x in range(0,len(sizes)):
resized = png.resize((sizes[x],sizes[x]), Image.ANTIALIAS)
resized.save('/tmp/transparent.png', quality=100)
upload_path = '%s/%s' % (name,sizes[x])
s3_client.put_object(Key='%s/transparent.png' % (upload_path), Bucket=output_bucket, Body=open('/tmp/transparent.png','rb'), ContentType='image/png')
for color in colors:
background = Image.new("RGBA",(sizes[x],ImageColor.getrgb(colors[color]))
background.paste(resized , resized)
filename = '/tmp/%s%s.jpg' % (sizes[x],color)
background.save(filename, quality=95)
s3_client.put_object(Key='%s/%s.jpg' % (upload_path,color), Body=open(filename, ContentType='image/jpeg')
def general_image(self, image_format='PNG'):
fm_width = self.cleaned_data['width']
fm_height = self.cleaned_data['height']
key = '{}.{}.{}'.format(fm_width, fm_height, image_format)
content = cache.get(key)
if content is None:
image = Image.new('RGB', (fm_width, fm_height), color=122)
draw = ImageDraw.Draw(image)
text = '{}x{}'.format(fm_width, fm_height)
text_width, text_height = draw.textsize(text)
if text_width < fm_width and text_height < fm_height:
text_top = (fm_height - text_height) // 2
text_left = (fm_width - text_width) // 2
draw.text((text_top, text_left), 255))
content = BytesIO()
image.save(content, image_format)
content.seek(0)
cache.set(key, content, 60 * 60)
return content
def get_mask(self, fill=1, outline=0):
"""
Get a mask that is nonzero within the object.
:param fill: A color to use on the object's interior
:param outline: A color to use on the object's edge (single pixel)
:return: A 2D numpy array of uint8
"""
if self.type in (TYPE_polyGON, TYPE_BOUNDING_Box):
(top, left, bottom, right) = self.polygon.bounds()
w = right-left
h = bottom-top
mask = Image.new("I", h))
d = ImageDraw.Draw(mask)
d.polygon([(px-left, py-top) for (px, py) in self.polygon.points],
fill=fill, outline=outline)
del d
return np.asarray(mask)
else:
assert False, "Unhandled Type"
def __init__(self, annotation, nrows=512, ncols=None):
super(SingleLayerLabels, self).__init__()
self.annotation = annotation
assert annotation.imagesize.nrows is not None, "Must kNow the image size first (see update_image_size)"
self.aspect = annotation.imagesize.ncols/float(annotation.imagesize.nrows)
self.y_scale = nrows / float(annotation.imagesize.nrows)
self.nrows = nrows
if ncols is None:
self.x_scale = self.y_scale
self.ncols = int(self.x_scale*annotation.imagesize.ncols)
else:
self.x_scale = ncols / float(annotation.imagesize.ncols)
self.ncols = ncols
self.image = Image.new('L', (self.ncols, self.nrows), LABEL_NEGATIVE)
self.artist = ImageDraw.Draw(self.image)
def create_wallpaper(screen, urls, size=(100, randomise=False):
if randomise:
random.shuffle(urls)
wallpaper = Image.new("RGB", screen, "blue")
width = int(math.ceil(float(screen[0]) / size[0]))
height = int(math.ceil(float(screen[1]) / size[1]))
offset = [0,0]
for i in xrange(height):
y = size[1] * i
for j in xrange(width):
x = size[0] * j
photo = load_photo(urls.pop())
if photo.size != size:
photo = photo.resize(size, Image.BICUBIC)
wallpaper.paste(photo, y))
del photo
return wallpaper
def get_temp_image():
image = Image.new("RGB", 100))
tmp_file = tempfile.NamedTemporaryFile(suffix=".jpg")
image.save(tmp_file)
tmp_file.seek(0)
return tmp_file
def make_iteration_image(state):
pixel_size = 9
image = Image.new('RGB', (state.board.cols * pixel_size, state.board.rows * pixel_size))
for row in range(state.board.rows):
for col in range(state.board.cols):
cell_image = get_cell_image(state.board.get_item((row, col)))
image.paste(cell_image, (col * pixel_size, row * pixel_size))
return image
def paletteImage(self):
""" PIL weird interface for making a paletted image: create an image which
already has the palette,and use that in Image.quantize. This function
returns this palette image. """
if self.pimage is None:
palette = []
for i in range(self.NETSIZE):
palette.extend(self.colormap[i][:3])
palette.extend([0]*(256-self.NETSIZE)*3)
# a palette image to use for quant
self.pimage = Image.new("P", (1, 0)
self.pimage.putpalette(palette)
return self.pimage
def _create_map_image(self):
images = self._get_images()
self._map_image = Image.new('RGBA', self._map_size)
for img in images:
if not isinstance(img, Image.Image):
img = Image.open(BytesIO(img.content)).convert('RGBA')
self._map_image = Image.alpha_composite(self._map_image, img)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。