poster image not displaying with add_movie() in python-pptx - powerpoint

I am trying to insert some sound files into a presentation, and the sound file seems to save fine, but the display image is always the default play button logo. Is there something wrong with my code, or is it another issue. I am currently working in a linux environment, if that makes any difference. I have tried with both mp4 and mp3 and the image issue is the same. The small play bar also seems not to appear although the sound file is in the presentation.
from pptx import Presentation
from pptx.util import Inches
prs = Presentation()
title_slide_layout = prs.slide_layouts[0]
slide = prs.slides.add_slide(title_slide_layout)
prs.slides[0].shapes.add_movie("sample2.mp3",
left = Inches(1), top = Inches(1), width = Inches(1), height = Inches(1),
poster_frame_image = "cat.jpeg"
)
prs.save('sound_image.pptx')

You can easily add any sound files to presentations and set poster images for them by using Aspose.Slides for Python as shown below:
import aspose.slides as slides
presentation_path = "example.pptx"
audio_path = "sample2.mp3"
image_path = "cat.jpeg"
with slides.Presentation() as presentation:
slide = presentation.slides[0]
# Add an audio frame to the slide with a specified position and size.
with open(audio_path, 'rb') as audio_stream:
audio_frame = slide.shapes.add_audio_frame_embedded(150, 100, 50, 50, audio_stream)
# Add the image to presentation resources.
with open(image_path, 'rb') as image_stream:
audio_image = presentation.images.add_image(image_stream)
# Set the image as the audio poster.
audio_frame.picture_format.picture.image = audio_image
presentation.save(presentation_path, slides.export.SaveFormat.PPTX)
I work as a Support Developer at Aspose.

Related

find template image in directory of images

I have a directory of images and an image that I know is in this image directory there is a similar image in the directory saved in a different format and scaled differently, but I dont know where (about 100 000 images).
I want to look for the image and find out its filename inside this directory.
I am looking for a mostly already made soulution which I couldn't find. I found OpenCV but I would need to write code around that. Is there a project like that out there?
If there isn't could you help me make a simple C# console app using OpenCV, I tried their templates but never managed to get SURF or CudaSURF working.
Thanks
Edited as per #Mark Setchell's comment
If the image is identical, the fastest way is to get the file size of the image you are looking for and compare it with the file sizes of the images amongst which you are searching.
I suggest this first because, as Christoph clarifies in the comments, it doesn't require reading the file at all - it is just metadata.
If that yields more than one matching answer, calculate a hash (MD5 or other) and pick the filename that produces the same hash.
Again, as mentioned by Christoph in the comments, this doesn't require decoding the image, or holding the decompressed image in RAM, just checksumming it.
So in the end I used this site and modified the python code used there for searching a directory instead of a single image. There is not much code so the full thing is below:
import argparse
from ast import For, arg
import cv2
from os import listdir
from os.path import isfile, join
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", type=str, required=True,
help="path to input image where we'll apply template matching")
ap.add_argument("-t", "--template", type=str, required=True,
help="path to template image")
args = vars(ap.parse_args())
# load the input image and template image from disk
print("[INFO] loading template...")
template = cv2.imread(args["template"])
cv2.namedWindow("Output")
cv2.startWindowThread()
# Display an image
cv2.imshow("Output", template)
cv2.waitKey(0)
# convert both the image and template to grayscale
templateGray = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
imageFileNames = [f for f in listdir(args["image"]) if isfile(join(args["image"], f))]
for imageFileName in imageFileNames:
try:
imagePath = args["image"] + imageFileName
print("[INFO] Loading " + imagePath + " from disk...")
image = cv2.imread(imagePath)
print("[INFO] Converting " + imageFileName + " to grayscale...")
imageGray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
print("[INFO] Performing template matching for " + imageFileName + "...")
result = cv2.matchTemplate(imageGray, templateGray,
cv2.TM_CCOEFF_NORMED)
(minVal, maxVal, minLoc, maxLoc) = cv2.minMaxLoc(result)
(startX, startY) = maxLoc
endX = startX + template.shape[1]
endY = startY + template.shape[0]
if maxVal > 0.75:
print("maxVal = " + str(maxVal))
# draw the bounding box on the image
cv2.rectangle(image, (startX, startY), (endX, endY), (255, 0, 0), 3)
# show the output image
cv2.imshow("Output", image)
cv2.waitKey(0)
cv2.imshow("Output", template)
except KeyboardInterrupt:
break
except:
print(imageFileName)
print("Error")
cv2.destroyAllWindows()
The code above shows any image with match value (what I guess is how much similarity there is between source and template) greater than 0.75
Probably still too low but if you want to use it tweak it to your liking.
Note that this WILL NOT work if the image is rotated and if, like me, you have a bright light source in the template other lightsources will come up as false positives
As for time it took me about 7 hours, where the script paused about every 20 minutes for a false positive until I found my image. I got through about 2/3 of all images.
as a sidenote it took 10 minutes to just build the array of files inside the directory, and it took about 500mb of ram once done
This is not the best answer so if anyone more qualified finds this feel free to write another answer.

Copy slide with images python pptx

My end goal is to change the theme of a presentation. To do this, I have created a source template and new template (with the correct theme). I iterate over each slide in the source template then add a new slide to the new template with the contents of the source using the code below - source. If there is a better way to do this I'd love to hear it.
This works great for text and text boxes, however the test image cannot be displayed in the new powerpoint (show in the image below):
Code
def copy_slide_from_external_prs(self, src, idx, newPrs):
# specify the slide you want to copy the contents from
src_slide = src.slides[idx]
# Define the layout you want to use from your generated pptx
slide_layout = newPrs.slide_layouts[2]
# create now slide, to copy contents to
curr_slide = newPrs.slides.add_slide(slide_layout)
# remove placeholders
for p in [s.element for s in curr_slide.shapes if 'Text Placeholder' in s.name or 'Title' in s.name]:
p.getparent().remove(p)
# now copy contents from external slide, but do not copy slide properties
# e.g. slide layouts, etc., because these would produce errors, as diplicate
# entries might be generated
for shp in src_slide.shapes:
el = shp.element
newel = copy.deepcopy(el)
curr_slide.shapes._spTree.insert_element_before(newel, 'p:extLst')
return newPrs
I was trying many different solutions and tried creating a new Picture using the image.blob property in the source image. However, then the image does not have an element. Do I need to convert the blob to a PNG, save it, then create a new image using that saved PNG?
There must be a better way to do this. Again, I just want to change the theme.
Thanks in advance!
Here is the workaround I developed. I first check if the shape is an image, and if it is, I write the image to a local directory. Then I add a picture to the slide using that saved image. Finally, I delete the locally saved image.
Now this copy_slide function works for images:
def copy_slide_from_external_prs(src, idx, newPrs):
# specify the slide you want to copy the contents from
src_slide = src.slides[idx]
# Define the layout you want to use from your generated pptx
SLD_LAYOUT = 5
slide_layout = prs.slide_layouts[SLD_LAYOUT]
# create now slide, to copy contents to
curr_slide = newPrs.slides.add_slide(slide_layout)
# create images dict
imgDict = {}
# now copy contents from external slide, but do not copy slide properties
# e.g. slide layouts, etc., because these would produce errors, as diplicate
# entries might be generated
for shp in src_slide.shapes:
if 'Picture' in shp.name:
# save image
with open(shp.name+'.jpg', 'wb') as f:
f.write(shp.image.blob)
# add image to dict
imgDict[shp.name+'.jpg'] = [shp.left, shp.top, shp.width, shp.height]
else:
# create copy of elem
el = shp.element
newel = copy.deepcopy(el)
# add elem to shape tree
curr_slide.shapes._spTree.insert_element_before(newel, 'p:extLst')
# add pictures
for k, v in imgDict.items():
curr_slide.shapes.add_picture(k, v[0], v[1], v[2], v[3])
os.remove(k)
Using code from #Michael-Berk I made very elegant method for copying slides (including images). Check this answer: https://stackoverflow.com/a/73954830/20159015

Moviepy Rendered Video File Doesn't Have any Sound

I have just taken a simple video clip and made a rendered video of it using moviepy. This is my code :
import moviepy.editor as mpe
video_clip = mpe.VideoFileClip("video.mp4")
audio_clip = mpe.AudioFileClip("closer.mp3")
video_clip.to_videofile("testingaudio.mp4",audio_codec = 'aac',audio = True)
The video is created. I even played it in VLC but there is no audio in it.
You need to add the audio clip to the video clip before writing it to a file.
Example:
import moviepy.editor as mpe
video_clip = mpe.VideoFileClip("video.mp4")
audio_clip = mpe.AudioFileClip("closer.mp3")
video_clip = video_clip.set_audio(audio_clip)
video_clip.write_videofile("testingaudio.mp4", audio_codec='aac')

Python: update plot with image with slider weight

I loaded a .nii file in my application.
def show(self):
image = SimpleITK.ReadImage(file_name)
t1 = SimpleITK.GetArrayFromImage(image)
t2 = color.rgb2gray(t1[w.get()])
print(w.get())
print(t2.shape)
plt.ion()
fig = plt.figure()
ax = fig.add_subplot(111)
line1 = ax.imshow(t2, cmap='gray')
This function it is called when I move the slider and show me in a new figure the slice of brain.(the screenshot of application is attach here: [1]: https://i.stack.imgur.com/vzDJt.png)
I need to update the same figure/plot, it is possible?
That should work, but I would not be calling ReadImage and GetArrayFromImage every time show gets called. You don't want to be re-loading and converting the image each time your widget changes. Do those thing once, when the application starts.
If you look at the SimpleITK-Notebooks that's pretty much how images are displayed in Jupyter notebooks.
http://insightsoftwareconsortium.github.io/SimpleITK-Notebooks/Python_html/04_Image_Display.html
The section 'Inline display with matplotlib' uses imshow to display images.

Image Misalignment in Visual Studio application

I have a Visual Studio application with a splash screen image cut into "slices". The positions are specified in the Form Designer so they line up properly on the screen. However, the images are out of place when the application is run on the Chinese version of Windows XP. It looks as if the image slices were "exploded" apart.
What's going on here? Do international versions of Windows have a different meaning of the "top left" coordinate of the picture? How can I force the images to be precisely displayed where I want them?
We found a solution! Apparently the picture boxes stretched out on the Chinese XP PC, but the images they contained did not. The fix was to add code like the following:
Me.PictureBoxIcon.Width = Me.PictureBoxIcon.Image.Width
Me.PictureBoxIcon.Height = Me.PictureBoxIcon.Image.Height
Dim loc As New Point
loc.X = Me.PictureBoxIcon.Location.X
loc.Y = Me.PictureBoxIcon.Location.Y + Me.PictureBoxIcon.Height
Me.PictureBoxAbout.Location = loc
Me.PictureBoxAbout.Width = Me.PictureBoxAbout.Image.Width
Me.PictureBoxAbout.Height = Me.PictureBoxAbout.Image.Height
Hope this helps someone else!
In the OnLoad event of the form, you could always explicitly set the location of each section. If starting at the top left with the first and assuming an array with the images in order:
images[0].Location = new Point(0,0);
for (int i = 1; i < images.Length; i++)
{
images[i].Location = new Point(images[i - 1].Location.X + images[i - 1].Width, 0);
}
That will set the first image to the top left corner and all subsequent images to just after the last image.

Resources