def convert(width,height):
im = Image.open("C:\\xxx\\test.jpg")
out = im.resize((width, height),Image.ANTIALIAS)
out.save("C:\\xxx\\test.jpg")
python类open()的实例源码
def play(self, sender):
# self.mode = console.alert('Race mode',
# button1='1. Blind draw',
# button2='2. Timed vectors'
# )
self.hide_all()
#self.show_play_menu() dialog
self.show_edit_view()
self.load_actual(burn_waypoints_in=True)
with io.BytesIO(self.edit_view.img.to_png()) as fp:
playfield = pilImage.open(fp).resize((int(self.bg.width), int(self.bg.height))).load()
for layer in self.play_layers:
layer.set_map(self.edit_view.waypoints, playfield, self.multiplier)
self.show_play_layers()
self.turn = -1
self.next_turn()
def load_texture(image_file, repeat=False):
"""Carga una textura desde un archivo image_file"""
img = Image.open(image_file)
data = numpy.array(list(img.getdata()), numpy.int8)
tex = glGenTextures(1)
glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
glBindTexture(GL_TEXTURE_2D, tex)
if repeat:
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
else:
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img.size[0], img.size[1], 0, GL_RGB, GL_UNSIGNED_BYTE, data)
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE)
return tex
def get_colors(f, do_shuffle=True):
try:
import Image
except Exception:
from PIL import Image
scale = 1./255.
im = Image.open(f)
data = list(im.convert('RGB').getdata())
res = []
for r,g,b in data:
res.append([r*scale,g*scale,b*scale])
if do_shuffle:
from numpy.random import shuffle
shuffle(res)
return res
def get_colors_from_file(self, fn):
import Image
from numpy.random import shuffle
def p(f):
return float('{:0.5f}'.format(f))
scale = 1./255.
im = Image.open(fn)
w, h = im.size
rgbim = im.convert('RGB')
res = []
for i in range(0, w):
for j in range(0, h):
r, g, b = rgbim.getpixel((i, j))
res.append([p(r*scale), p(g*scale), p(b*scale)])
shuffle(res)
self.colors = res
self.ncolors = len(res)
def create_thumb(img_name):
image = Image.open('{}.tiff'.format(img_name))
(imageW, imageH) = image.size
if imageW > imageH:
ratio = thumb_size / imageW
newWidth = 400
newHeight = int(imageH * ratio)
else:
ratio = thumb_size / imageH
newHeight = 400
newWidth = int(imageW * ratio)
image = image.resize((newWidth, newHeight), Image.LANCZOS)
outfh = open('{}_thumb.tiff'.format(img_name), 'wb')
image.save(outfh, format='TIFF')
outfh.close()
def clean_zip_file(self):
"""Open the zip file a first time, to check that it is a valid zip archive.
We'll open it again in a moment, so we have some duplication, but let's focus
on keeping the code easier to read!
"""
zip_file = self.cleaned_data['zip_file']
try:
zip = zipfile.ZipFile(zip_file)
except BadZipFile as e:
raise forms.ValidationError(str(e))
bad_file = zip.testzip()
if bad_file:
zip.close()
raise forms.ValidationError('"%s" in the .zip archive is corrupt.' % bad_file)
zip.close() # Close file in all cases.
return zip_file
def check_md5sum_change(src_file):
"""Returns True if src_file has a different md5sum"""
src_md5 = get_md5sum(src_file)
src_md5_file = src_file + '.md5'
src_file_changed = True
if os.path.exists(src_md5_file):
with open(src_md5_file, 'r') as file_checksum:
ref_md5 = file_checksum.read()
if src_md5 == ref_md5:
src_file_changed = False
if src_file_changed:
with open(src_md5_file, 'w') as file_checksum:
file_checksum.write(src_md5)
return src_file_changed
def image_file_to_string(filename, cleanup = cleanup_scratch_flag, graceful_errors=True):
"""Applies tesseract to filename; or, if image is incompatible and graceful_errors=True,
converts to compatible format and then applies tesseract. Fetches resulting text.
If cleanup=True, delete scratch files after operation."""
try:
try:
call_tesseract(filename, scratch_text_name_root)
text = util.retrieve_text(scratch_text_name_root)
except errors.Tesser_General_Exception:
if graceful_errors:
im = Image.open(filename)
text = image_to_string(im, cleanup)
else:
raise
finally:
if cleanup:
util.perform_cleanup(scratch_image_name, scratch_text_name_root)
return text
def genLines(image=None):
PrintGood('This is going to return OCR on either a list of images or full images')
if isinstance(image, list) == False:
image = PromptList('Which image/images to OCR: ', image)
Found = []
for image in image:
image = Image.open(image)
with PyTessBaseAPI() as api:
api.SetImage(image)
boxes = api.GetComponentImages(RIL.TEXTLINE, True)
print 'Found {} textline image components.'.format(len(boxes))
for i, (im, box, _, _) in enumerate(boxes):
# im is a PIL image object
# box is a dict with x, y, w and h keys
api.SetRectangle(box['x'], box['y'], box['w'], box['h'])
ocrResult = api.GetUTF8Text().split(' ')
conf = api.MeanTextConf()
ocrResult = [word.strip() for word in ocrResult]
Found.append(ocrResult)
print (u"Box[{0}]: x={x}, y={y}, w={w}, h={h}, "
"confidence: {1}, text: {2}").format(i, conf, ocrResult, **box)
return Found
def Spaces(image=None):
PrintGood('This returns the number of spaces in a specific image or images')
if isinstance(image, list) == False:
image = PromptList('Which image/images to Scan: ', image)
for image in image:
image = Image.open(image)
with PyTessBaseAPI() as api:
api.SetImage(image)
boxes = api.GetComponentImages(RIL.TEXTLINE, True)
Spaces = 0
for i, (im, box, _, _) in enumerate(boxes):
im.save('saving{}.jpg'.format(i))
api.SetRectangle(box['x'], box['y'], box['w'], box['h'])
ocrResult = api.GetUTF8Text()
conf = api.MeanTextConf()
text = str(ocrResult).replace('\n', '').split(' ')
Spaces = len(text) + Spaces
return int(Spaces)
def ocrToDict(image=None, listofwords=[]):
#image can be a list of files
Words = {}
if len(listofwords) == 0:
PrintFail('You need to input a list of words')
if 'y' in str(raw_input("Do you want to search for lyrics now? ")).lower():
artist = raw_input("Artist: ")
song = raw_input("Song: ")
listofwords = GrabSongLyrics(artist, song)
print(listofwords)
else:
return
if isinstance(image, list) == False:
image = PromptList('Which image/images to Scan: ', image)
for i, image in enumerate(image):
Words['Clean'][i] = imageToOCR(image, listofwords)
with open('{}Transcript.json'.format(Words[1]), 'w') as f:
json.dump(Words, f)
def WriteToImage(output, txt, size=45, input='background.jpg'):
output = str(output).replace('.png', '').replace('.jpg', '')
i = Image.open(input)
font = ImageFont.load_default()
txt = txt.split(' ')
r = []
for part in txt:
r.append(str(part).replace(' ', ''))
txt = r
a = ''
while len(txt) > 0:
try:
for e in range(7):
item = txt[0]
txt.remove(item)
a = a + ' ' + str(item)
a = a + '\n'
except:
break
text_col = (255, 255, 255) # bright green
halo_col = (0, 0, 0) # black
i2 = draw_text_with_halo(i, (20, 40), a, font, text_col, halo_col)
i2.save('{}.png'.format(output))
def insert_text(img, dest, msg):
image = Image.open(img)
width, height = image.size
if image.mode[:3] != "RGB" or width * height * 3 < len(msg) + RESERVED_PIXELS * 3:
raise IndexError("Unable to use this picture")
bits = bin(len(msg))[2:].zfill(RESERVED_PIXELS * 3)
msg = bits + msg
msg = enumerate(msg + "0" * (3 - len(msg) % 3))
p = image.load()
for i, j in pixels(image.size):
try:
rgb = map(lambda color, bit: color - (color % 2) + int(bit), p[i, j][:3], [msg.next()[1] for _ in xrange(3)])
p[i, j] = tuple(rgb)
except StopIteration:
image.save(dest, "PNG", quality = 100)
return
def extract_text(img):
image = Image.open(img)
length = image.size
p = image.load()
leng = ""
for pix in pixels(length):
leng += "".join("1" if color % 2 else "0" for color in p[pix][:3])
if len(leng) >= RESERVED_PIXELS * 3:
leng = int(leng, 2)
break
binary_information = ""
for pix in pixels(length):
binary_information += "".join("1" if color % 2 else "0" for color in p[pix][:3])
return binary_information[RESERVED_PIXELS * 3 : leng + RESERVED_PIXELS * 3]
def create_py(self, nb, force=False):
"""Create the python script from the notebook node"""
# Although we would love to simply use ``nbconvert.export_python(nb)``
# this causes troubles in other cells processed by the ipython
# directive. Instead of getting something like ``Out [5]:``, we get
# some weird like '[0;31mOut[[1;31m5[0;31m]: [0m' which look like
# color information if we allow the call of nbconvert.export_python
if list(map(int, re.findall('\d+', nbconvert.__version__))) >= [4, 2]:
py_file = os.path.basename(self.py_file)
else:
py_file = self.py_file
spr.call(['jupyter', 'nbconvert', '--to=python',
'--output=' + py_file, '--log-level=%s' % logger.level,
self.outfile])
with open(self.py_file) as f:
py_content = f.read()
# comment out ipython magics
py_content = re.sub('^\s*get_ipython\(\).magic.*', '# \g<0>',
py_content, flags=re.MULTILINE)
with open(self.py_file, 'w') as f:
f.write(py_content)
def _parsejpg(self, filename):
# Extract info from a JPEG file
if Image is None:
self.error('PIL not installed')
try:
f = open(filename, 'rb')
im = Image.open(f)
except Exception, e:
self.error('Missing or incorrect image file: %s. error: %s' % (filename, str(e)))
else:
a = im.size
# We shouldn't get into here, as Jpeg is RGB=8bpp right(?), but, just in case...
bpc=8
if im.mode == 'RGB':
colspace='DeviceRGB'
elif im.mode == 'CMYK':
colspace='DeviceCMYK'
else:
colspace='DeviceGray'
# Read whole file from the start
f.seek(0)
data = f.read()
f.close()
return {'w':a[0],'h':a[1],'cs':colspace,'bpc':bpc,'f':'DCTDecode','data':data}
def _parsegif(self, filename):
# Extract info from a GIF file (via PNG conversion)
if Image is None:
self.error('PIL is required for GIF support')
try:
im = Image.open(filename)
except Exception, e:
self.error('Missing or incorrect image file: %s. error: %s' % (filename, str(e)))
else:
# Use temporary file
f = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
tmp = f.name
f.close()
if "transparency" in im.info:
im.save(tmp, transparency = im.info['transparency'])
else:
im.save(tmp)
info = self._parsepng(tmp)
os.unlink(tmp)
return info
def setupTexturemaps(self):
this_folder = os.path.dirname(os.path.abspath(__file__))
image_path = os.path.join(this_folder, "cube_texture_small.png")
img = Image.open(image_path)
imageRGBA = numpy.array(list(img.getdata()), numpy.uint8)
self.m_iTexture = glGenTextures(1)
glBindTexture( GL_TEXTURE_2D, self.m_iTexture )
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, img.size[0], img.size[1],
0, GL_RGB, GL_UNSIGNED_BYTE, imageRGBA )
glGenerateMipmap(GL_TEXTURE_2D)
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE )
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE )
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR )
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR )
fLargest = glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, fLargest)
glBindTexture( GL_TEXTURE_2D, 0 )
return self.m_iTexture != 0
def _parsejpg(self, filename):
# Extract info from a JPEG file
if Image is None:
self.error('PIL not installed')
try:
f = open(filename, 'rb')
im = Image.open(f)
except Exception, e:
self.error('Missing or incorrect image file: %s. error: %s' % (filename, str(e)))
else:
a = im.size
# We shouldn't get into here, as Jpeg is RGB=8bpp right(?), but, just in case...
bpc=8
if im.mode == 'RGB':
colspace='DeviceRGB'
elif im.mode == 'CMYK':
colspace='DeviceCMYK'
else:
colspace='DeviceGray'
# Read whole file from the start
f.seek(0)
data = f.read()
f.close()
return {'w':a[0],'h':a[1],'cs':colspace,'bpc':bpc,'f':'DCTDecode','data':data}
def _parsegif(self, filename):
# Extract info from a GIF file (via PNG conversion)
if Image is None:
self.error('PIL is required for GIF support')
try:
im = Image.open(filename)
except Exception, e:
self.error('Missing or incorrect image file: %s. error: %s' % (filename, str(e)))
else:
# Use temporary file
f = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
tmp = f.name
f.close()
if "transparency" in im.info:
im.save(tmp, transparency = im.info['transparency'])
else:
im.save(tmp)
info = self._parsepng(tmp)
os.unlink(tmp)
return info
def _get_data(url):
"""Helper function to get data over http or from a local file"""
if url.startswith('http://'):
resp = urllib2.urlopen(url)
encoding = resp.headers.dict.get('content-encoding', 'plain')
data = resp.read()
if encoding == 'plain':
pass
elif encoding == 'gzip':
data = StringIO(data)
data = gzip.GzipFile(fileobj=data).read()
else:
raise RuntimeError('unknown encoding')
else:
with open(url, 'r') as fid:
data = fid.read()
fid.close()
return data
def decode(self, filename=None):
self.filename = filename or self.filename
if self.filename:
scanner = zbar.ImageScanner()
# configure the reader
scanner.parse_config('enable')
# obtain image data
pil = Image.open(self.filename).convert('L')
width, height = pil.size
try:
raw = pil.tobytes()
except AttributeError:
raw = pil.tostring()
# wrap image data
image = zbar.Image(width, height, 'Y800', raw)
# scan the image for barcodes
result = scanner.scan(image)
# extract results
if result == 0:
return False
else:
for symbol in image:
pass
# clean up
del(image)
# Assuming data is encoded in utf8
self.data = symbol.data.decode(u'utf-8')
self.data_type = self.data_recognise()
return True
else:
return False
def _parsejpg(self, filename):
# Extract info from a JPEG file
if Image is None:
self.error('PIL not installed')
try:
f = open(filename, 'rb')
im = Image.open(f)
except Exception, e:
self.error('Missing or incorrect image file: %s. error: %s' % (filename, str(e)))
else:
a = im.size
# We shouldn't get into here, as Jpeg is RGB=8bpp right(?), but, just in case...
bpc=8
if im.mode == 'RGB':
colspace='DeviceRGB'
elif im.mode == 'CMYK':
colspace='DeviceCMYK'
else:
colspace='DeviceGray'
# Read whole file from the start
f.seek(0)
data = f.read()
f.close()
return {'w':a[0],'h':a[1],'cs':colspace,'bpc':bpc,'f':'DCTDecode','data':data}
def _parsegif(self, filename):
# Extract info from a GIF file (via PNG conversion)
if Image is None:
self.error('PIL is required for GIF support')
try:
im = Image.open(filename)
except Exception, e:
self.error('Missing or incorrect image file: %s. error: %s' % (filename, str(e)))
else:
# Use temporary file
f = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
tmp = f.name
f.close()
if "transparency" in im.info:
im.save(tmp, transparency = im.info['transparency'])
else:
im.save(tmp)
info = self._parsepng(tmp)
os.unlink(tmp)
return info
def get_colors(f, do_shuffle=True):
from numpy import array
try:
import Image
except Exception:
from PIL import Image
im = Image.open(f)
data = array(list(im.convert('RGB').getdata()),'float')/255.0
res = []
for rgb in data:
res.append(list(rgb))
if do_shuffle:
from numpy.random import shuffle
shuffle(res)
return res
def binary(f): #????????
print f
img = Image.open(f)
#img = img.convert('1')
img = img.convert("RGBA") #???????????????????
pixdata = img.load()
for y in xrange(img.size[1]):
for x in xrange(img.size[0]):
if pixdata[x, y][0] < 90:
pixdata[x, y] = (0, 0, 0, 255)
for y in xrange(img.size[1]):
for x in xrange(img.size[0]):
if pixdata[x, y][1] < 136:
pixdata[x, y] = (0, 0, 0, 255)
for y in xrange(img.size[1]):
for x in xrange(img.size[0]):
if pixdata[x, y][2] > 0:
pixdata[x, y] = (255, 255, 255, 255)
return img
def _get_data(url):
"""Helper function to get data over http or from a local file"""
if url.startswith('http://'):
# Try Python 2, use Python 3 on exception
try:
resp = urllib.urlopen(url)
encoding = resp.headers.dict.get('content-encoding', 'plain')
except AttributeError:
resp = urllib.request.urlopen(url)
encoding = resp.headers.get('content-encoding', 'plain')
data = resp.read()
if encoding == 'plain':
pass
elif encoding == 'gzip':
data = StringIO(data)
data = gzip.GzipFile(fileobj=data).read()
else:
raise RuntimeError('unknown encoding')
else:
with open(url, 'r') as fid:
data = fid.read()
fid.close()
return data
def extract_line_count(filename, target_dir):
# Extract the line count of a file
example_file = os.path.join(target_dir, filename)
lines = open(example_file).readlines()
start_row = 0
if lines and lines[0].startswith('#!'):
lines.pop(0)
start_row = 1
line_iterator = iter(lines)
tokens = tokenize.generate_tokens(lambda: next(line_iterator))
check_docstring = True
erow_docstring = 0
for tok_type, _, _, (erow, _), _ in tokens:
tok_type = token.tok_name[tok_type]
if tok_type in ('NEWLINE', 'COMMENT', 'NL', 'INDENT', 'DEDENT'):
continue
elif (tok_type == 'STRING') and check_docstring:
erow_docstring = erow
check_docstring = False
return erow_docstring + 1 + start_row, erow + 1 + start_row
def substract_bg(self, bgpath):
bg = Image.open(bgpath)
img = self.img.convert("P")
bglut = bg.resize((256, 1))
bglut.putdata(range(256))
bglut = list(bglut.convert("RGB").getdata())
lut = img.resize((256, 1))
lut.putdata(range(256))
lut = list(lut.convert("RGB").getdata())
bgpix = bg.load()
pix = img.load()
orgpix = self.img.load()
for x in range(bg.size[0]):
for y in range(bg.size[1]):
rgb_bg = bglut[bgpix[x, y]]
rgb_c = lut[pix[x, y]]
if rgb_c == rgb_bg:
orgpix[x, y] = (255, 255, 255)