Related
from pptx import Presentation
prs = Presentation(my_file)
print(prs.slides[1].shape[0])
#out:
#<pptx.shapes.picture.Picture at 0x2295816cf98>
I need to loop through my shapes and assign a custom height, width and vertical position :
height = 7002000
width = 12193200
i have my height + width values which I can set via assignment prs.slides[1].shape[0].height = height
with a simple loop.
one thing I can't find is the attribute to set the shape's position on the page, chiefly the Vertical Position
my correct value is set to -0.16cm which I'm trying to replicate.
I thought it might be under left or top but my correct presentation returns a value of 0
Note that you can use the provided convenience measurements like this:
from pptx.util import Cm
shape.left = Cm(5.5)
Which saves you doing the arithmetic to English Metric Units (EMU) yourself.
Found the answer finally - I had to use a combination of top and left on the shape attribute.
in my case I had to set my variables to
top = -57600
left = 0
I then access the shape method
for slide in prs.slides:
for shape in slide.shapes:
shape.left = left
shape.top = top
def new_presentation():
prs=Presentation()
img="C:/Users/Dennis/Desktop/Tom-Hiddleston-4-1024x768.jpg"
mainsld=new_slide(prs, 6)
mainshp=mainsld.shapes
mainshp.add_picture(img, 0,0, Inches(10))
titleshape=mainshp.add_shape(MSO_SHAPE.RECTANGLE, Inches(0), Inches(1), Inches(10), Inches(1))
titleshape.fill.solid()
titleshape.fill.fore_color.rgb=RGBColor(0x00,0x64,0x00)
titleshape.fill.transparency = 0.25 ##doesnt work???##########################
titleshape.line.fill.background()
titlebox=mainshp.add_textbox(Inches(1), Inches(0.8),Inches(1), Inches(1)).text_frame.add_paragraph()
titlebox.text="TOM HIDDLESTON"
titlebox.font.name="Calibri"
titlebox.font.size=Pt(36)
titlebox.font.color.rgb=RGBColor(0x90,0x90,0x00)
prs.save('test.pptx')
The line marked with "######s" is supposed to make the shape more transparent as written in the pptx documentation - it is a shape.fill property . Everything else in the code works perfectly. I'm using python 2.7 and latest pptx. Thank you for your help in advance.
After much digging, I have been able to come up with a solution for this
from pptx import Presentation
from pptx.oxml.xmlchemy import OxmlElement
from pptx.util import Cm
from pptx.enum.shapes import MSO_SHAPE
from pptx.dml.color import RGBColor
def SubElement(parent, tagname, **kwargs):
element = OxmlElement(tagname)
element.attrib.update(kwargs)
parent.append(element)
return element
def _set_shape_transparency(shape, alpha):
""" Set the transparency (alpha) of a shape"""
ts = shape.fill._xPr.solidFill
sF = ts.get_or_change_to_srgbClr()
sE = SubElement(sF, 'a:alpha', val=str(alpha))
## Create presentation
prs = Presentation()
## Add a slide (empty slide layout)
slide = prs.slides.add_slide(prs.slide_layouts[6])
##Add a blue box to the slide
blueBox = slide.shapes.add_shape(autoshape_type_id=MSO_SHAPE.RECTANGLE,
left=Cm(0),
top=Cm(0),
height=Cm(10),
width=Cm(20))
## Make the box blue
blueBoxFill = blueBox.fill
blueBoxFill.solid()
blueBoxFillColour = blueBoxFill.fore_color
blueBoxFillColour.rgb = RGBColor(0,176,240)
## Set the transparency of the blue box to 56%
_set_shape_transparency(blueBox,44000)
## Save the presentation
prs.save(your_path)
FillFormat.transparency is not implemented yet. The part of the documentation where you saw that may have been an analysis page, which is a precursor to development.
This is the analysis page:
http://python-pptx.readthedocs.io/en/latest/dev/analysis/features/dml-fill.html?highlight=transparency
This is the FillFormat (.fill) API, as developed:
http://python-pptx.readthedocs.io/en/latest/api/dml.html#fillformat-objects
You can however use lxml calls from the FillFormat object to manipulate the XML under it. You probably want to start with the spPr element in the .fill element:
spPr = titleshape.fill._xPr
print spPr.xml
Here's one example of doing that sort of thing:
https://groups.google.com/forum/#!msg/python-pptx/UTkdemIZICw/qeUJEyKEAQAJ
You'll find more if you search on various combinations of the terms python-pptx, OxmlElement, lxml, and workaround function.
I am trying to draw a textured square using Python, OpenGL and GLFW.
Here are all the images I need to show you.
Sorry for the way of posting images, but I don't have enough reputation to post more than 2 links (and I can't even post a photo).
I am getting this:
[the second image from the album]
Instead of that:
[the first image from the album]
BUT if I use some different jpg files:
some of them are being displayed properly,
some of them are being displayed properly until I rotate them 90 degrees (I mean using numpy rot90 function on an array with RGB components) and then send them to the GPU. And it looks like that (colors don't change, I only get some distortion):
Before rotation:
[the third image from the album]
After rotation:
[the fourth image from the album]
It all depends on a file.
Does anybody know what I do wrong? Or see anything that I don't see?
Code:
First, I do the thing with initializing glfw, creating a window, etc.
if __name__ == '__main__':
import sys
import glfw
import OpenGL.GL as gl
import numpy as np
from square import square
from imio import imread,rgb_flag,swap_rb
from txio import tx2gpu,txrefer
glfw.glfwInit()
win =glfw.glfwCreateWindow(800,800,"Hello")
glfw.glfwMakeContextCurrent(win)
glfw.glfwSwapInterval(1)
gl.glClearColor(0.75,0.75,0.75,1.0)
Then I load an image using OpenCV imread function and I remember about swapping red with blue. Then I send the image to gpu - I will describe tx2gpu in a minute.
image = imread('../imtools/image/ummagumma.jpg')
if not rgb_flag: swap_rb(image)
#image = np.rot90(image)
tx_id = tx2gpu(image)
The swap_rb() function (defined in a different file, imported):
def swap_rb(mat):
X = mat[:,:,2].copy()
mat[:,:,2] = mat[:,:,0]
mat[:,:,0] = X
return mat
Then comes the main loop (in a while I will describe txrefer and square):
while not glfw.glfwWindowShouldClose(win):
gl.glClear(gl.GL_COLOR_BUFFER_BIT)
txrefer(tx_id); square(2); txrefer(0)
glfw.glfwSwapBuffers(win)
glfw.glfwPollEvents()
And here is the end of the main function:
glfw.glfwDestroyWindow(win)
glfw.glfwTerminate()
NOW IMPORTANT THINGS:
A function that defines a square looks like that:
def square(scale=1.0,color=None,solid=True):
s = scale*.5
if type(color)!=type(None):
if solid:
gl.glBegin(gl.GL_TRIANGLE_FAN)
else:
gl.glBegin(gl.GL_LINE_LOOP)
gl.glColor3f(*color[0][:3]); gl.glVertex3f(-s,-s,0)
gl.glColor3f(*color[1][:3]); gl.glVertex3f(-s,s,0)
gl.glColor3f(*color[2][:3]); gl.glVertex3f(s,s,0)
gl.glColor3f(*color[3][:3]); gl.glVertex3f(s,-s,0)
else:
if solid:
gl.glBegin(gl.GL_TRIANGLE_FAN)
else:
gl.glBegin(gl.GL_LINE_LOOP)
gl.glTexCoord2f(0,0); gl.glVertex3f(-s,-s,0)
gl.glTexCoord2f(0,1); gl.glVertex3f(-s,s,0)
gl.glTexCoord2f(1,1); gl.glVertex3f(s,s,0)
gl.glTexCoord2f(1,0); gl.glVertex3f(s,-s,0)
gl.glEnd()
And texturing functions look like that:
import OpenGL.GL as gl
unit_symbols = [
gl.GL_TEXTURE0,gl.GL_TEXTURE1,gl.GL_TEXTURE2,
gl.GL_TEXTURE3,gl.GL_TEXTURE4,
gl.GL_TEXTURE5,gl.GL_TEXTURE6,gl.GL_TEXTURE7,
gl.GL_TEXTURE8,gl.GL_TEXTURE9,
gl.GL_TEXTURE10,gl.GL_TEXTURE11,gl.GL_TEXTURE12,
gl.GL_TEXTURE13,gl.GL_TEXTURE14,
gl.GL_TEXTURE15,gl.GL_TEXTURE16,gl.GL_TEXTURE17,
gl.GL_TEXTURE18,gl.GL_TEXTURE19,
gl.GL_TEXTURE20,gl.GL_TEXTURE21,gl.GL_TEXTURE22,
gl.GL_TEXTURE23,gl.GL_TEXTURE24,
gl.GL_TEXTURE25,gl.GL_TEXTURE26,gl.GL_TEXTURE27,
gl.GL_TEXTURE28,gl.GL_TEXTURE29,
gl.GL_TEXTURE30,gl.GL_TEXTURE31]
def tx2gpu(image,flip=True,unit=0):
gl.glActiveTexture(unit_symbols[unit])
texture_id = gl.glGenTextures(1)
gl.glBindTexture(gl.GL_TEXTURE_2D,texture_id)
gl.glTexParameteri(gl.GL_TEXTURE_2D,gl.GL_TEXTURE_WRAP_S,gl.GL_REPEAT)
gl.glTexParameteri(gl.GL_TEXTURE_2D,gl.GL_TEXTURE_WRAP_T,gl.GL_REPEAT)
gl.glTexParameteri(gl.GL_TEXTURE_2D,gl.GL_TEXTURE_MAG_FILTER,gl.GL_LINEAR)
gl.glTexParameteri(gl.GL_TEXTURE_2D,gl.GL_TEXTURE_MIN_FILTER,gl.GL_LINEAR)
yres,xres,cres = image.shape
from numpy import flipud
gl.glTexImage2D(gl.GL_TEXTURE_2D,0,gl.GL_RGB,xres,yres,0,gl.GL_RGB,gl.GL_UNSIGNED_BYTE,flipud(image))
gl.glBindTexture(gl.GL_TEXTURE_2D,0)
return texture_id
def txrefer(tex_id,unit=0):
gl.glColor4f(1,1,1,1);
gl.glActiveTexture(unit_symbols[unit])
if tex_id!=0:
gl.glEnable(gl.GL_TEXTURE_2D)
gl.glBindTexture(gl.GL_TEXTURE_2D,tex_id)
else:
gl.glBindTexture(gl.GL_TEXTURE_2D,0)
gl.glDisable(gl.GL_TEXTURE_2D)
The problem you have there are alignment issues. OpenGL initial alignment setting for "unpacking" images is that each row starts on a 4 byte boundary. This happens if the image width is not a multiple of 4 or if there are not 4 bytes per pixel. But it's easy enough to change this:
glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
would probably do the trick for you. Call it right before glTex[Sub]Image.
Another thing: Your unit_symbols list is completely unnecessary. The OpenGL specification explicitly says that GL_TEXTUREn = GL_TEXTURE0 + n. You can simply do glActiveTexture(GL_TEXTURE0 + n). However when loading a texture image the unit is completely irrelevant; the only thing it may matter is, that loading a texture only goes with binding one, which happens in a texture unit; a texture can be bound in any texture unit desired.
Personally I use the highest texture unit for loading images, to avoid accidently clobbering required state.
I have the results of a simulation on an unstructured 2D mesh. I usually export the results in VTK and visualize them with Paraview. This is what results look like.
I would like to obtain a raster image from the results (with or without interpolation) to use it as a texture for visualization in a 3D software. From reading around I have gathered that I need to do some kind of resampling in order to convert from the unstructured grid to a 2d regular grid for the raster image.
VTK can export to raster, but it exports only a full scene without any defined boundary so it requires manual tweaking to fit the image.
Ideally I would like to export only the results within the results bounding box and 'map' them to a raster image programmatically with Ruby or Python.
This script uses paraview and creates an image perfectly centered and scaled so that it can be used as a texture. Notice the 855 value for the vertical size. It seems to be related to the resolution of the screen and it is needed only on OSX according to Paraview mailing list.
It should be run to the Paraview Python interpreter pvbatch.
import sys, json
#### import the simple module from the paraview
from paraview.simple import *
#### disable automatic camera reset on 'Show'
paraview.simple._DisableFirstRenderCameraReset()
args = json.loads(sys.argv[1])
# create a new 'Legacy VTK Reader'
vtk_file = args["file"]
data = LegacyVTKReader(FileNames=[vtk_file])
# get active view
renderView1 = GetActiveViewOrCreate('RenderView')
# uncomment following to set a specific view size
xc = float(args["center"][0])
yc = float(args["center"][1])
zc = float(args["center"][2])
width = float(args["width"])
height = float(args["height"])
output_file = args["output_file"]
scalar = args["scalar"]
colormap_min = float(args["colormap_min"])
colormap_max = float(args["colormap_max"])
ratio = height / width
magnification = 2
height_p = 855 * magnification
width_p = int(height_p * 1.0 / ratio / magnification)
renderView1.ViewSize = [width_p , height_p]
# show data in view
dataDisplay = Show(data, renderView1)
# trace defaults for the display properties.
dataDisplay.ColorArrayName = ['CELLS', scalar]
# set scalar coloring
ColorBy(dataDisplay, ('CELLS', scalar))
# rescale color and/or opacity maps used to include current data range
dataDisplay.RescaleTransferFunctionToDataRange(True)
# get color transfer function/color map for 'irradiation'
irradiationLUT = GetColorTransferFunction(scalar)
# Rescale transfer function
irradiationLUT.RescaleTransferFunction(colormap_min, colormap_max)
irradiationLUT.LockDataRange = 1
irradiationLUT.ColorSpace = 'RGB'
irradiationLUT.NanColor = [0.498039, 0.0, 0.0]
#changing interaction mode based on data extents
renderView1.InteractionMode = '2D'
renderView1.CameraPosition = [xc, yc, 10000.0 + zc]
renderView1.CameraFocalPoint = [xc, yc, zc]
# hide color bar/color legend
dataDisplay.SetScalarBarVisibility(renderView1, False)
# current camera placement for renderView1
renderView1.InteractionMode = '2D'
#renderView1.CameraPosition = [3.641002, 197.944122, 10001.75]
#renderView1.CameraFocalPoint = [3.641002, 197.944122, 1.75]
renderView1.CameraParallelScale = (height / 2.0)
# save screenshot
SaveScreenshot(output_file, magnification=magnification, quality=100, view=renderView1)
I have a DIY solution. Usually, I do as follows:
Open my mesh as a polygon layer in QGIS and do the following:
calculate mesh centroids in QGIS (Vector/Geometry Tools/Polygon Centroids)
right click on the newly created layer, select Save As, select CSV format and under Layer options/GEOMETRY select xy or xyz
Then, with a simple python script I associate the vtk data (like e.g. water depth) to the centroids (be aware that ParaView numbers the nodes with a -1 offset in respect to QGIS, so node 2 in ParaView is node 3 in QGIS).
Eventually, again in QGIS, I interpolate a raster from vector points e.g. with the GRASSS GIS module v.to.rast.attribute
I'm writing a program that will allow me to upload photos to TUMBLR via their API, I've got the uploading working (thanks to you guys).
I've put a 'queueBox' on the side of the GUI, which displays the image names, and they are stored in a QListWidget. I've put this in my Main Class' constructor:
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.setupUi(self)
self.queueBox.itemClicked.connect(self.displayPhoto)
and I have this method:
def displayPhoto(self, item):
tempName = (item.text())
print tempName
self.myLabel.setPixmap(QtGui.QPixmap(_fromUtf8(directory + '\\' + tempName)))
## self.myLabel.pixmap(QPixmap.scaled(aspectRatioMode = Qt.IgnoreAspectRatio))
## ^ ^ ^ What do I do with this? How do I set it to maintain aspect ratio?
## Currently it says ''NameError: global name 'Qt' is not defined''
This sucessfully draws the image on to myLabel which is a QLabel, however, It is very scaled, I have
self.myLabel.setScaledContents(True)
in my ui_mainWindow class, and if I turn it to False, it fixes the scaling but it only shows a small portion of the image because the image is much larger than the QLabel. What I want is to be able to maintain the aspect ratio, so it doesn't look scaled and horrible.
I found this: http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qpixmap.html
and it says how to use it, however I can't get it to work as shown in the code above in my comments. Does anyone know how to use this? If so, can you provide me with an example, I've tried searching but most of the results I get are working examples in C++, not python.
Thanks!
Get rid of the
self.myLabel.setScaledContents(True)
call (or set it to False). It is filling your widget with the pixmap without caring about the aspect ratio.
If you need to resize a QPixmap, as you have found, scaled is the required method. But you are invoking it wrong. Let's look at the definition:
QPixmap QPixmap.scaled (self,
int width,
int height,
Qt.AspectRatioMode aspectRatioMode = Qt.IgnoreAspectRatio,
Qt.TransformationMode transformMode = Qt.FastTransformation)
Return type of this function is QPixmap, so it returns a scaled copy of the original pixmap.
Then you need a width and a height, describing the (maximum) final size of the pixmap.
Two more optional parameters. aspectRatioMode deals with the, well aspect ratio. The documentation details the different options and their effects. transformMode defines how (which algorithm) the scaling is done. It might change the final quality of your image. You probably don't need this one.
So, putting it together you should have (Qt namespace is inside QtCore):
# substitute the width and height to desired values
self.myLabel.setPixmap(QtGui.QPixmap(_fromUtf8(directory + '\\' + tempName)).scaled(width, height, QtCore.Qt.KeepAspectRatio))
Alternatively, if you have a fixed size QLabel, you could call the .size() method to get the size from it:
self.myLabel.setPixmap(QtGui.QPixmap(_fromUtf8(directory + '\\' + tempName)).scaled(self.myLabel.size(), QtCore.Qt.KeepAspectRatio))
Note: You might want to use os.path.join(directory, tempName) for the directory + '\\' + tempName part.
PyQt5 code change update:
The above answer of avaris needed a PyQt5 update because it breaks.
QPixmap.scaled (self, int width, int height, Qt.AspectRatioMode aspectRatioMode = Qt.IgnoreAspectRatio
Keeping the self in the code results in below traceback error.
TypeError: arguments did not match any overloaded call: scaled(self, int, int, aspectRatioMode: Qt.AspectRatioMode = Qt.IgnoreAspectRatio, transformMode: Qt.TransformationMode = Qt.FastTransformation): argument 1 has unexpected type 'MainUI' scaled(self, QSize, aspectRatioMode: Qt.AspectRatioMode = Qt.IgnoreAspectRatio, transformMode: Qt.TransformationMode = Qt.FastTransformation): argument 1 has unexpected type 'MainUI'
Thus this should be (without "self", "Qt") as stated below:
QPixmap.scaled (int width, int height, aspectRatioMode = IgnoreAspectRatio
or:
QPixmap.scaled (int width, int height, aspectRatioMode = 0)
KeepAspectRatio = 2... but used as provided by aspectRatioMode = 2 in above code. Enjoy!