本文整理汇总了Python中panda3d.core.PNMImage.write方法的典型用法代码示例。如果您正苦于以下问题:Python PNMImage.write方法的具体用法?Python PNMImage.write怎么用?Python PNMImage.write使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类panda3d.core.PNMImage
的用法示例。
在下文中一共展示了PNMImage.write方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from panda3d.core import PNMImage [as 别名]
# 或者: from panda3d.core.PNMImage import write [as 别名]
def main():
sff_file =''
output_dir=''
if len(sys.argv) >= 2:
sff_file = sys.argv[1]
else:
logging.error('Usage: sff-test ssf_file [output_dir]')
return
if len(sys.argv) >= 3:
output_dir = sys.argv[2]
#checking output dir
if (output_dir != '') and (not os.path.exists(output_dir)):
os.makedirs(output_dir)
else:
logging.info("Output directory not set from command line, skipping image save")
fh = open(sff_file, 'rb')
header = sff1_file.parse(fh.read(512))
print(header)
next_subfile = header.next_subfile
count = 0
while next_subfile and count < header.image_total:
fh.seek(next_subfile)
subfile = sff1_subfile_header.parse(fh.read(32))
next_subfile = subfile.next_subfile
try:
buff = StringIO(fh.read(subfile.length))
image = Image.open(buff)
buff = StringIO()
image.save(buff,'PNG')
output = PNMImage()
if not output.read(StringStream(buff.getvalue()), "i.png"):
logging.error("Failed to read image from buffer")
raise ValueError("Invalid image!")
print("Image Group: %i, no: %i, size: %i x %i ,offset: (%i , %i), palette %i"%(subfile.groupno,subfile.imageno,
image.size[0],image.size[1],subfile.axisx,subfile.axisy,subfile.palette))
except IOError:
print(("ioerror", subfile.groupno, subfile.imageno))
pass
else:
# image.save(output_dir + "/g{0}-i{1}.png".format(subfile.groupno, subfile.imageno))
if len(output_dir) > 0:
output.write(output_dir + "/g{0}-i{1}.png".format(subfile.groupno, subfile.imageno))
count+=1
示例2: filter_cubemap
# 需要导入模块: from panda3d.core import PNMImage [as 别名]
# 或者: from panda3d.core.PNMImage import write [as 别名]
def filter_cubemap(orig_pth):
if not os.path.isdir("Filtered/"):
os.makedirs("Filtered/")
# Copy original cubemap
for i in range(6):
shutil.copyfile(orig_pth.replace("#", str(i)), "Filtered/0-" + str(i) + ".png")
mip = 0
while True:
print("Filtering mipmap", mip)
mip += 1
pth = "Filtered/" + str(mip - 1) + "-#.png"
dst_pth = "Filtered/" + str(mip) + "-#.png"
first_img = load_nth_face(pth, 0)
size = first_img.get_x_size() // 2
if size < 1:
break
blur_size = size * 0.002
blur_size += mip * 0.85
blur_size = int(blur_size)
effective_size = size + 2 * blur_size
faces = [load_nth_face(pth, i) for i in range(6)]
cubemap = loader.loadCubeMap(pth)
node = NodePath("")
node.set_shader(compute_shader)
node.set_shader_input("SourceCubemap", cubemap)
node.set_shader_input("size", size)
node.set_shader_input("blurSize", blur_size)
node.set_shader_input("effectiveSize", effective_size)
final_img = PNMImage(size, size, 3)
for i in range(6):
face_dest = dst_pth.replace("#", str(i))
dst = Texture("Face-" + str(i))
dst.setup_2d_texture(effective_size, effective_size,
Texture.T_float, Texture.F_rgba16)
# Execute compute shader
node.set_shader_input("faceIndex", i)
node.set_shader_input("DestTex", dst)
attr = node.get_attrib(ShaderAttrib)
base.graphicsEngine.dispatch_compute(( (effective_size+15) // 16,
(effective_size+15) // 16, 1),
attr, base.win.get_gsg())
base.graphicsEngine.extract_texture_data(dst, base.win.get_gsg())
img = PNMImage(effective_size, effective_size, 3)
dst.store(img)
img.gaussian_filter(blur_size)
final_img.copy_sub_image(img, 0, 0, blur_size, blur_size, size, size)
final_img.write(face_dest)
示例3: generate_atlas
# 需要导入模块: from panda3d.core import PNMImage [as 别名]
# 或者: from panda3d.core.PNMImage import write [as 别名]
def generate_atlas(files, dest_dat, dest_png):
entries = []
virtual_atlas_size = 32
all_entries_matched = False
print("Loading", len(files), "entries ..")
for verbose_name, source in files:
entries.append(AtlasEntry(verbose_name, source))
entries = sorted(entries, key=lambda a: -a.area)
while not all_entries_matched:
print("Trying to pack into a", virtual_atlas_size, "x", virtual_atlas_size, "atlas ..")
packer = LUIAtlasPacker(virtual_atlas_size)
all_entries_matched = True
for entry in entries:
print("Finding position for", entry.w, entry.h)
uv = packer.find_position(entry.w, entry.h)
if uv.get_x() < 0:
# print " Not all images matched, trying next power of 2"
all_entries_matched = False
virtual_atlas_size *= 2
break
entry.assigned_pos = uv
print("Matched entries, writing atlas ..")
atlas_description_content = ""
dest = PNMImage(virtual_atlas_size, virtual_atlas_size, 4)
for entry in entries:
if not entry.tex.has_alpha():
entry.tex.add_alpha()
entry.tex.alpha_fill(1.0)
dest.copy_sub_image(
entry.tex, int(entry.assigned_pos.get_x()), int(entry.assigned_pos.get_y()))
atlas_description_content += "{0} {1} {2} {3} {4}\n".format(
entry.name.replace(" ", "_"),
int(entry.assigned_pos.get_x()),
int(entry.assigned_pos.get_y()),
entry.w, entry.h)
print("Writing", entry.name,"with dimensions", entry.w, entry.h)
dest.write(dest_png)
with open(dest_dat, "w") as handle:
handle.write(atlas_description_content)
示例4: getScreenshot
# 需要导入模块: from panda3d.core import PNMImage [as 别名]
# 或者: from panda3d.core.PNMImage import write [as 别名]
def getScreenshot(p3dApp):
p3dApp.taskMgr.step()
p3dApp.taskMgr.step()
pnmss = PNMImage()
p3dApp.win.getScreenshot(pnmss)
resulting_ss = StringStream()
pnmss.write(resulting_ss, "screenshot.png")
screenshot_buffer = resulting_ss.getData()
pilimage = Image.open(StringIO(screenshot_buffer))
pilimage.load()
#pnmimage will sometimes output as palette mode for 8-bit png so convert
pilimage = pilimage.convert('RGBA')
return pilimage
示例5: load_3d_texture
# 需要导入模块: from panda3d.core import PNMImage [as 别名]
# 或者: from panda3d.core.PNMImage import write [as 别名]
def load_3d_texture(cls, fname, tile_size_x, tile_size_y=None, num_tiles=None):
""" Loads a texture from the given filename and dimensions. If only
one dimensions is specified, the other dimensions are assumed to be
equal. This internally loads the texture into ram, splits it into smaller
sub-images, and then calls the load_3d_texture from the Panda loader """
# Generate a unique name to prevent caching
tempfile_name = "$$SliceLoaderTemp-" + str(time.time()) + "/"
# For quaddratic textures
tile_size_y = tile_size_x if tile_size_y is None else tile_size_y
num_tiles = tile_size_x if num_tiles is None else num_tiles
# Load sliced image from disk
source = PNMImage(fname)
width = source.get_x_size()
# Find slice properties
num_cols = width // tile_size_x
temp = PNMImage(
tile_size_x, tile_size_y, source.get_num_channels(), source.get_maxval())
# Construct a ramdisk to write the files to
vfs = VirtualFileSystem.get_global_ptr()
ramdisk = VirtualFileMountRamdisk()
vfs.mount(ramdisk, tempfile_name, 0)
# Extract all slices and write them to the virtual disk
for z_slice in range(num_tiles):
slice_x = (z_slice % num_cols) * tile_size_x
slice_y = (z_slice // num_cols) * tile_size_y
temp.copy_sub_image(source, 0, 0, slice_x, slice_y, tile_size_x, tile_size_y)
temp.write(tempfile_name + str(z_slice) + ".png")
# Load the de-sliced texture from the ramdisk
texture_handle = Globals.loader.load3DTexture(tempfile_name + "/#.png")
# This should never trigger, but can't hurt to have
assert texture_handle.get_x_size() == tile_size_x
assert texture_handle.get_y_size() == tile_size_y
assert texture_handle.get_z_size() == num_tiles
# Finally unmount the ramdisk
vfs.unmount(ramdisk)
return texture_handle
示例6: load_sliced_3d_texture
# 需要导入模块: from panda3d.core import PNMImage [as 别名]
# 或者: from panda3d.core.PNMImage import write [as 别名]
def load_sliced_3d_texture(cls, fname, tile_size_x, tile_size_y=None, num_tiles=None):
""" Loads a texture from the given filename and dimensions. If only
one dimensions is specified, the other dimensions are assumed to be
equal. This internally loads the texture into ram, splits it into smaller
sub-images, and then calls the load_3d_texture from the Panda loader """
tempfile_name = "/$$slice_loader_temp-" + str(time.time()) + "/"
tile_size_y = tile_size_x if tile_size_y is None else tile_size_y
num_tiles = tile_size_x if num_tiles is None else num_tiles
# Load sliced image from disk
source = PNMImage(fname)
width = source.get_x_size()
# Find slice properties
num_cols = width // tile_size_x
temp_img = PNMImage(
tile_size_x, tile_size_y, source.get_num_channels(), source.get_maxval())
# Construct a ramdisk to write the files to
vfs = VirtualFileSystem.get_global_ptr()
ramdisk = VirtualFileMountRamdisk()
vfs.mount(ramdisk, tempfile_name, 0)
# Extract all slices and write them to the virtual disk
for z_slice in range(num_tiles):
slice_x = (z_slice % num_cols) * tile_size_x
slice_y = (z_slice // num_cols) * tile_size_y
temp_img.copy_sub_image(source, 0, 0, slice_x, slice_y, tile_size_x, tile_size_y)
temp_img.write(tempfile_name + str(z_slice) + ".png")
# Load the de-sliced texture from the ramdisk
texture_handle = cls.load_3d_texture(tempfile_name + "/#.png")
vfs.unmount(ramdisk)
return texture_handle
示例7: str
# 需要导入模块: from panda3d.core import PNMImage [as 别名]
# 或者: from panda3d.core.PNMImage import write [as 别名]
content = content.replace("%ENDIF_" + def_name + "%", "")
else:
content = content.replace("%IF_" + def_name + "%", "<!--")
content = content.replace("%ENDIF_" + def_name + "%", "-->")
content = content.replace("%ALPHA%", str(material["roughness"] * material["roughness"]))
content = content.replace("%IOR%", str(material.get("ior", 1.51)))
content = content.replace("%BASECOLOR%", str(material["basecolor"]).strip("()"))
content = content.replace("%MATERIAL_SRC%", material.get("material_src", "").strip("()"))
with open("res/scene.xml", "w") as handle:
handle.write(content)
os.system("run_mitsuba.bat > nul")
print(" Writing result ..")
img = PNMImage("scene-rp.png")
img_ref = PNMImage("scene.png")
img.copy_sub_image(img_ref, 256, 0, 256, 0, 256, 512)
img.mult_sub_image(overlay, 0, 0)
img.write("batch_compare/" + material["name"] + ".png")
try:
os.remove("_tmp_material.py")
except:
pass
print("Done!")
示例8: enumerate
# 需要导入模块: from panda3d.core import PNMImage [as 别名]
# 或者: from panda3d.core.PNMImage import write [as 别名]
for i, s_nxv in enumerate(reversed(nxv_values)):
if NxV >= s_nxv:
index = i
break
index = len(nxv_values) - index - 1
next_index = index + 1 if index < dest_size - 1 else index
curr_nxv = nxv_values[index]
next_nxv = nxv_values[next_index]
lerp_factor = (NxV - curr_nxv) / max(1e-10, abs(next_nxv - curr_nxv))
lerp_factor = max(0.0, min(1.0, lerp_factor))
indices.append((index, next_index, lerp_factor))
# Generate the final linear lut using the lerp weights
for y in xrange(dest_h):
for x in xrange(dest_size):
curr_i, next_i, lerp = indices[x]
curr_v = img.get_xel(curr_i, y)
next_v = img.get_xel(next_i, y)
dest.set_xel(x, y, curr_v * (1 - lerp) + next_v * lerp)
out_name = config["out_name"].replace("{}", str(pass_index))
dest.write(config["out_dir"] + "/" + out_name)
try:
os.remove("scene.png")
except:
pass
示例9: PNMImage
# 需要导入模块: from panda3d.core import PNMImage [as 别名]
# 或者: from panda3d.core.PNMImage import write [as 别名]
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
from __future__ import division, print_function
import math
from panda3d.core import PNMImage
lut_size = 64
lut_cols = 8
lut_rows = (lut_size + lut_cols - 1) // lut_cols
img = PNMImage(lut_size * lut_cols, lut_size * lut_rows, 3, 2**16 - 1)
def to_linear(v):
return float(v) / float(lut_size-1)
def to_linear_inv(v):
return 1 - to_linear(v)
for r in range(lut_size):
for g in range(lut_size):
for b in range(lut_size):
slice_offset_x = (b % lut_cols) * lut_size
slice_offset_y = (b // lut_cols) * lut_size
img.set_xel(r + slice_offset_x, g + slice_offset_y,
to_linear(r), to_linear_inv(g), to_linear(b))
img.write("DefaultLUT.png")
示例10: xrange
# 需要导入模块: from panda3d.core import PNMImage [as 别名]
# 或者: from panda3d.core.PNMImage import write [as 别名]
for k in xrange(3):
values[k].append(srgb_to_linear(line[k]))
def to_linear(v):
return float(v) / float(64 - 1)
def to_linear_inv(v):
return 1 - to_linear(v)
def lookup_value(v, values):
return values[int(v * (len(values) - 1))]
# Generate lut
img = PNMImage(64 * 8, 64 * 8, 3, 2**16 - 1)
for r in xrange(64):
for g in xrange(64):
for b in xrange(64):
slice_offset_x = (b % 8) * 64
slice_offset_y = (b // 8) * 64
fr, fg, fb = to_linear(r), to_linear_inv(g), to_linear(b)
fr = lookup_value(fr, values[0])
fg = lookup_value(fg, values[1])
fb = lookup_value(fb, values[2])
img.set_xel(r + slice_offset_x, g + slice_offset_y, fr, fg, fb)
img.write("film_luts/" + output_name + ".png")
示例11: PNMImage
# 需要导入模块: from panda3d.core import PNMImage [as 别名]
# 或者: from panda3d.core.PNMImage import write [as 别名]
write_diff_img = False
img_a = PNMImage(source_a)
img_b = PNMImage(source_b)
w, h = img_a.get_x_size(), img_a.get_y_size()
img_dest = PNMImage(w, h, 3)
error_scale = 10.0
total_diff = 0.0
for x in xrange(w):
for y in xrange(h):
val_a = img_a.get_xel(x, y)
val_b = img_b.get_xel(x, y)
abs_diff = (val_a - val_b) * error_scale
r, g, b = abs(abs_diff.x), abs(abs_diff.y), abs(abs_diff.z)
img_dest.set_xel(x, y, r, g, b)
total_diff += r + g + b
total_diff /= float(w * h)
total_diff /= error_scale
print("Average difference: ", total_diff, " in RGB: ", total_diff * 255)
img_dest.write("difference.png")
示例12: __init__
# 需要导入模块: from panda3d.core import PNMImage [as 别名]
# 或者: from panda3d.core.PNMImage import write [as 别名]
def __init__(self, pipeline):
DebugObject.__init__(self, "BugReporter")
self.debug("Creating bug report")
reportDir = "BugReports/" + str(int(time.time())) + "/"
reportFname = "BugReports/" + str(int(time.time())) + ""
if not isdir(reportDir):
os.makedirs(reportDir)
# Generate general log
DebugLog = "Pipeline Bug-Report\n"
DebugLog += "Created: " + datetime.datetime.now().isoformat() + "\n"
DebugLog += "System: " + sys.platform + " / " + os.name + " (" + str(8 * struct.calcsize("P")) + " Bit)\n"
with open(join(reportDir, "general.log"), "w") as handle:
handle.write(DebugLog)
# Write stdout and stderr
with open(join(reportDir, "stdout.log"), "w") as handle:
handle.write(sys.stdout.getLog())
with open(join(reportDir, "stderr.log"), "w") as handle:
handle.write(sys.stderr.getLog())
# Write the scene graph
handle = OFileStream(join(reportDir, "scene_graph.log"))
Globals.render.ls(handle)
handle.close()
# Write the pipeline settings
SettingLog = "# Pipeline Settings Diff File:\n\n"
for key, val in pipeline.settings.settings.iteritems():
if val.value != val.default:
SettingLog += key + " = " + str(val.value) + " (Default " + str(val.default) + ")\n"
with open(join(reportDir, "pipeline.ini"), "w") as handle:
handle.write(SettingLog)
# Write the panda settings
handle = OFileStream(join(reportDir, "pandacfg.log"))
ConfigVariableManager.getGlobalPtr().writePrcVariables(handle)
handle.close()
# Write lights and shadow sources
with open(join(reportDir, "lights.log"), "w") as handle:
pp = pprint.PrettyPrinter(indent=4, stream=handle)
handle.write("\nLights:\n")
pp.pprint(pipeline.lightManager.lightSlots)
handle.write("\n\nShadowSources:\n")
pp.pprint(pipeline.lightManager.shadowSourceSlots)
# Extract buffers
bufferDir = join(reportDir, "buffers")
if not isdir(bufferDir):
os.makedirs(bufferDir)
for name, (size, entry) in MemoryMonitor.memoryEntries.iteritems():
if type(entry) == Texture:
w, h = entry.getXSize(), entry.getYSize()
# Ignore buffers
if h < 2:
continue
pipeline.showbase.graphicsEngine.extractTextureData(entry, pipeline.showbase.win.getGsg())
if not entry.hasRamImage():
print "Ignoring", name
continue
pnmSrc = PNMImage(w, h, 4, 2 ** 16 - 1)
entry.store(pnmSrc)
pnmColor = PNMImage(w, h, 3, 2 ** 16 - 1)
pnmColor.copySubImage(pnmSrc, 0, 0, 0, 0, w, h)
pnmColor.write(join(bufferDir, name + "-color.png"))
pnmAlpha = PNMImage(w, h, 3, 2 ** 16 - 1)
pnmAlpha.copyChannel(pnmSrc, 3, 0)
pnmAlpha.write(join(bufferDir, name + "-alpha.png"))
shutil.make_archive(reportFname, "zip", reportDir)
shutil.rmtree(reportDir)
self.debug("Bug report saved: ", reportFname + ".zip")
示例13: PNMImage
# 需要导入模块: from panda3d.core import PNMImage [as 别名]
# 或者: from panda3d.core.PNMImage import write [as 别名]
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
from __future__ import division, print_function
import math
from panda3d.core import PNMImage
lut_size = 64
lut_cols = 8
lut_rows = (lut_size + lut_cols - 1) // lut_cols
img = PNMImage(lut_size * lut_cols, lut_size * lut_rows, 3, 2**16 - 1)
def to_linear(v):
return float(v) / float(lut_size-1)
def to_linear_inv(v):
return 1 - to_linear(v)
for r in range(lut_size):
for g in range(lut_size):
for b in range(lut_size):
slice_offset_x = (b % lut_cols) * lut_size
slice_offset_y = (b // lut_cols) * lut_size
img.set_xel(r + slice_offset_x, g + slice_offset_y,
to_linear(r), to_linear_inv(g), to_linear(b))
img.write("default_lut.png")
示例14: PNMImage
# 需要导入模块: from panda3d.core import PNMImage [as 别名]
# 或者: from panda3d.core.PNMImage import write [as 别名]
from panda3d.core import PNMImage, Vec3
lutSize = 32
image = PNMImage(lutSize * lutSize, lutSize, 3, 2**16 - 1)
for r in xrange(lutSize):
for g in xrange(lutSize):
for b in xrange(lutSize):
image.setXel(r + b * lutSize, g, r / float(lutSize), g / float(lutSize), b / float(lutSize))
image.write("Default.png")