Python PIL.Image 模块,fromstring() 实例源码
我们从Python开源项目中,提取了以下13个代码示例,用于说明如何使用PIL.Image.fromstring()。
def test_pil_plugins(pyi_builder):
pyi_builder.test_source(
"""
# Verify packaging of PIL.Image. Specifically,the hidden import of FixTk
# importing tkinter is causing some problems.
from PIL.Image import fromstring
print(fromstring)
# PIL import hook should bundle all available PIL plugins. Verify that plugins
# are bundled.
from PIL import Image
Image.init()
MIN_PLUG_COUNT = 7 # Without all plugins the count is usually 6.
plugins = list(Image.SAVE.keys())
plugins.sort()
if len(plugins) < MIN_PLUG_COUNT:
raise SystemExit('No PIL image plugins were bundled!')
else:
print('PIL supported image formats: %s' % plugins)
""")
def index_image_es(Metadata):
preview_image_url, original_image_url, search_term, index_name = Metadata
image = None
if preview_image_url is None:
return
if preview_image_url.startswith("data:"):
pass
# data = preview_image_url[preview_image_url.find(",")+1:]
# data = base64.b64decode(data)
# Image.fromstring()
# image = Image.open(data)
elif preview_image_url.startswith("https://encrypted"):
image = get_image_from_url(preview_image_url)
if image is not None:
chunk = original_image_url.split("/")
file_name = chunk[len(chunk)-1]
Metadata = (preview_image_url, search_term)
try:
index_image(image=image, file_name=file_name, index_name=index_name, Metadata=Metadata)
except Exception as ex:
print(ex)
pass
def test_pil_plugins(pyi_builder):
pyi_builder.test_source(
"""
# Verify packaging of PIL.Image. Specifically,the hidden import of FixTk
# importing tkinter is causing some problems.
from PIL.Image import fromstring
print(fromstring)
# PIL import hook should bundle all available PIL plugins. Verify that plugins
# are bundled.
from PIL import Image
Image.init()
MIN_PLUG_COUNT = 7 # Without all plugins the count is usually 6.
plugins = list(Image.SAVE.keys())
plugins.sort()
if len(plugins) < MIN_PLUG_COUNT:
raise SystemExit('No PIL image plugins were bundled!')
else:
print('PIL supported image formats: %s' % plugins)
""")
def getimage(self):
buffer, width, height = self.dev.getbuffer()
if buffer:
im = Image.fromstring('RGB', (width, height), buffer, 'raw', 'BGR', 0, -1)
return im
def on_image(self, item):
# Rate limit
curr_time = time.time()
if (curr_time - self.last_update) < self.min_update_interval:
return
self.last_update = curr_time
rospy.loginfo("Posting image")
image_format = self.image_format_mapping.get(item.encoding, None)
if image_format is None:
raise ValueError()
img = Image.fromstring(
image_format, (item.width, item.height), item.data
)
point = EnvironmentalDataPoint({
"environment": self.environment,
"variable": self.variable.name,
"is_desired": False,
"value": None,
"timestamp": time.time()
})
point_id, point_rev = self.db.save(point)
url = "{db_url}/{point_id}/image?rev={rev}".format(
db_url=self.db.resource.url, point_id=point_id, rev=point_rev
)
buf = StringIO()
img.save(buf, "PNG")
buf.seek(0)
headers = {
"Content-Type": "image/png"
}
res = requests.put(url, data=buf, headers=headers)
if res.status_code != 201:
raise RuntimeError(
"Failed to post image to database: {}".format(res.content)
)
def _test():
import EasyDialogs
try:
from PIL import Image
except ImportError:
Image = None
import MacOS
Qt.EnterMovies()
path = EasyDialogs.AskFileForOpen(message='Video to convert')
if not path: sys.exit(0)
rdr = reader(path)
if not rdr:
sys.exit(1)
dstdir = EasyDialogs.AskFileForSave(message='Name for output folder')
if not dstdir: sys.exit(0)
num = 0
os.mkdir(dstdir)
videofmt = rdr.GetVideoFormat()
imgfmt = videofmt.getformat()
imgw, imgh = videofmt.getsize()
timestamp, data = rdr.ReadVideo()
while data:
fname = 'frame%04.4d.jpg'%num
num = num+1
pname = os.path.join(dstdir, fname)
if not Image: print 'Not',
print 'Writing %s,size %dx%d,%d bytes'%(fname, imgw, imgh, len(data))
if Image:
img = Image.fromstring("RGBA", (imgw, imgh), data)
img.save(pname, 'JPEG')
timestamp, data = rdr.ReadVideo()
MacOS.SetCreatorAndType(pname, 'ogle', 'JPEG')
if num > 20:
print 'stopping at 20 frames so your disk does not fill up:-)'
break
print 'Total frames:', num
def _test():
import EasyDialogs
try:
from PIL import Image
except ImportError:
Image = None
import MacOS
Qt.EnterMovies()
path = EasyDialogs.AskFileForOpen(message='Video to convert')
if not path: sys.exit(0)
rdr = reader(path)
if not rdr:
sys.exit(1)
dstdir = EasyDialogs.AskFileForSave(message='Name for output folder')
if not dstdir: sys.exit(0)
num = 0
os.mkdir(dstdir)
videofmt = rdr.GetVideoFormat()
imgfmt = videofmt.getformat()
imgw, num
def _test():
import EasyDialogs
try:
from PIL import Image
except ImportError:
Image = None
import MacOS
Qt.EnterMovies()
path = EasyDialogs.AskFileForOpen(message='Video to convert')
if not path: sys.exit(0)
rdr = reader(path)
if not rdr:
sys.exit(1)
dstdir = EasyDialogs.AskFileForSave(message='Name for output folder')
if not dstdir: sys.exit(0)
num = 0
os.mkdir(dstdir)
videofmt = rdr.GetVideoFormat()
imgfmt = videofmt.getformat()
imgw, num
def apply_perspective_surf(self, surf):
self.invert_surface(surf)
data = pygame.image.tostring(surf, 'RGBA')
img = Image.fromstring('RGBA', surf.get_size(), data)
img = img.transform(img.size, self.affinestate.proj_type,
self.affinestate.sample_transformation(img.size),
Image.BICUBIC)
img = img.transform(img.size, self.perspectivestate.proj_type,
self.perspectivestate.sample_transformation(img.size),
Image.BICUBIC)
im = n.array(img)
surf = pygame.surfarray.make_surface(im[..., 0:3].swapaxes(0, 1))
self.invert_surface(surf)
return surf
def get_image(self):
data = pygame.image.tostring(self.screen, 'RGBA')
return n.array(Image.fromstring('RGBA', self.screen.get_size(), data))
def apply_perspective_surf(self, 1))
self.invert_surface(surf)
return surf
def get_image(self):
data = pygame.image.tostring(self.screen, data))
def save_image(path_or_fd, values, dynamic_range=None):
"""Try hard to save values as an image in *path_or_fd* using any available
helper tool.
Parameters
----------
path_or_fd : file or str
Open file object or file path.
values : ndarray
Image array any 2-D shape to be saved.
dynamic_range : 2-tuple of ints,optional
Dynamic range of saved image (min,max)
Raises
-------
ValueError
If called with an image path (type) that can't be saved with any of the
helper tools.
"""
path = extract_path(path_or_fd)
if dynamic_range:
(cmin, cmax) = (dynamic_range[0], dynamic_range[1])
else:
(cmin, cmax) = (values.min(), values.max())
try:
# PIL wrapper borrowed from scipy implementation
from PIL import Image
(low, high) = (0, 255)
scale = high * 1. / (cmax - cmin or 1)
bytedata = ((values * 1. - cmin) * scale + 0.4999).astype(uint8)
bytedata += cast[uint8](low)
# shape is opposite of wanted image layout
shape = values.shape[::-1]
img = Image.fromstring('L', shape, bytedata.tostring())
img.save(path_or_fd)
return
except ImportError:
pass
try:
# Plain scipy - please note that this import may leak GPU memory!!!
import scipy.misc
scipy.misc.toimage(values, cmin=cmin,
cmax=cmax).save(path_or_fd)
return
except ImportError:
pass
raise ValueError('gave up saving image to %s - no suitable tools'
% path)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。