How do I add a shadow to AutoShapes using Python-pptx? - python

I just want to add a shadow to the shapes that I am creating while using python-pptx.
I have read as many documents about using shadows in python-pptx as I can find but I can not figure out how to actually do it.
I tried shadow = shape.shadow to create a 'ShadowFormat' object but when I try to do shadow.visible I get the error AttributeError: 'ShadowFormat' object has no attribute 'visible'
If anyone could explain how this is done and give an example it would be much appreciated!
Extra info:
This is the page linking to the topic: https://python-pptx.readthedocs.io/en/latest/dev/analysis/shp-shadow.html however there is no example on how to create a shadow for a shape in powerpoint.
I have imported the following modules:
from pptx import Presentation
from pptx.enum.shapes import MSO_SHAPE
from pptx.enum.action import PP_ACTION
from pptx.util import Cm
from pptx.enum.dml import MSO_THEME_COLOR_INDEX
from pptx.enum.text import MSO_AUTO_SIZE
from pptx.util import Pt
I am using python-pptx v0.6.18 and python v3.8
Edit
Example that creates the shape but no shadow appears:
#Import modules
from pptx import Presentation
from pptx.enum.shapes import MSO_SHAPE
from pptx.util import Cm
from pptx.enum.dml import MSO_THEME_COLOR_INDEX
from pptx.util import Pt
#Open powerpoint file
prs = Presentation('filename.pptx')
#Create a slide
slidelayout = prs.slide_layouts[0]
slide = prs.slides.add_slide(slidelayout)
shapes = slide.shapes
#Add a shape
shape = shapes.add_shape(MSO_SHAPE.ROUNDED_RECTANGLE, Cm(10), Cm(10), Cm(10), Cm(10))
#Create a shadow
shadow = shape.shadow
shadow.inherit = False
shadow.visible = True
shadow.distance = Pt(10)
shadow.shadow_type = 'outer'
shadow.angle = 45
shadow.blur_radius = Pt(5)
shadow.color = MSO_THEME_COLOR_INDEX.ACCENT_5
shadow.transparency = '50'
shadow.distance = Pt(5)
shape.shadow.style = 'outer'
#Save the powerpoint file
prs.save('filename2.pptx')
Example that creates the error message:
#Import modules
from pptx import Presentation
from pptx.enum.shapes import MSO_SHAPE
from pptx.util import Cm
from pptx.enum.dml import MSO_THEME_COLOR_INDEX
from pptx.util import Pt
#Open powerpoint file
prs = Presentation('filename.pptx')
#Create a slide
slidelayout = prs.slide_layouts[0]
slide = prs.slides.add_slide(slidelayout)
shapes = slide.shapes
#Add a shape
shape = shapes.add_shape(MSO_SHAPE.ROUNDED_RECTANGLE, Cm(10), Cm(10), Cm(10), Cm(10))
#Create a shadow
shadow = shape.shadow
shadow.visible
#Save the powerpoint file
prs.save('filename2.pptx')

The feature <ShadowFormat.visible - applies a reasonable standard shadow override.> is currently out of the scope of pptx.
The command <shadow.inherit = False> is used to remove the default setting with the shadow.
By default, the shadow visibility is set to true. If you want to show the shadow, you can either:
set <shadow.inherit = True>
remove <shadow.inherit = False>

You can use Aspose.Slides for Python to manipulate the shapes. This is a paid library, but you can get a temporary license to evaluate it. The following code example shows you how to add a shape with a shadow to a presentation:
import aspose.slides as slides
# Create a new presentation.
with slides.Presentation() as presentation:
# Create a shape.
shape = presentation.slides[0].shapes.add_auto_shape(slides.ShapeType.ROUND_CORNER_RECTANGLE, 10, 10, 20, 20)
# Set a shadow for the shape.
shape.effect_format.enable_outer_shadow_effect()
shape.effect_format.outer_shadow_effect.distance = 10
shape.effect_format.outer_shadow_effect.direction = 45
shape.effect_format.outer_shadow_effect.blur_radius = 5
shape.effect_format.outer_shadow_effect.shadow_color.color = presentation.master_theme.color_scheme.accent5.color
# Save the presentation.
presentation.save("example.pptx", slides.export.SaveFormat.PPTX)
The result:
Alternatively, you can use Aspose.Slides Cloud SDK for Python. This product provides a REST-based API for presentation processing. It is also a paid product, but you can make 150 free API calls per month for experimentation, learning, and any other purpose. The following code example creates the same shape with the shadow using Aspose.Slides Cloud:
import asposeslidescloud
from asposeslidescloud.apis.slides_api import SlidesApi
from asposeslidescloud.models.shape import Shape
from asposeslidescloud.models.effect_format import EffectFormat
from asposeslidescloud.models.outer_shadow_effect import OuterShadowEffect
slides_api = SlidesApi(None, "my_client_id", "my_client_secret")
# Let's a presentation exists in a storage.
file_name = "example.pptx"
slide_index = 1
color_scheme = slides_api.get_color_scheme(file_name, slide_index)
# Prepare DTO for a shape with the shadow.
shape = Shape()
shape.shape_type = "RoundCornerRectangle"
shape.x = 10
shape.y = 10
shape.width = 20
shape.height = 20
shape.effect_format = EffectFormat()
shape.effect_format.outer_shadow = OuterShadowEffect()
shape.effect_format.outer_shadow.distance = 10
shape.effect_format.outer_shadow.direction = 45
shape.effect_format.outer_shadow.blur_radius = 5
shape.effect_format.outer_shadow.shadow_color = color_scheme.accent5
# Create the shape.
slides_api.create_shape(file_name, slide_index, shape)
I work as a Support Developer at Aspose.

Related

Why my object detection output gives wrong names?

I am new in machine vision and i was trying to detect objects. I watched a YouTube video and i did exactly what the teacher did! He tried the code for car and person and also the only true output is related to pictures of car and person but i want to use it to detect fruits.
Also the code is:
import cv2
import matplotlib.pyplot as plt
import numpy as np
config_file = "ssd_mobilenet_v3_large_coco_2020_01_14.pbtxt"
frozen_model = "frozen_inference_graph.pb"
model = cv2.dnn_DetectionModel(frozen_model, config_file)
classlabels = []
file_name = 'labels.txt'
with open(file_name, 'rt') as fpt:
classlabels = fpt.read().rstrip('\n').split('\n')
model.setInputSize(320,320)
model.setInputScale(1.0/127.5)
model.setInputMean((127.5,127.5,127.5))
model.setInputSwapRB(True)
# Read the image
img = cv2.imread('person.jpg')
ClassIndex, confidence, bbox = model.detect(img, confThreshold=0.5)
print(ClassIndex)
font_scale = 3
font = cv2.FONT_HERSHEY_PLAIN
for ClassInd, conf, boxes in zip(ClassIndex.flatten(), confidence.flatten(), bbox):
cv2.rectangle(img,boxes,(255,0,0),2)
cv2.putText(img,classlabels[ClassInd-1],(boxes[0]+10,boxes[1]+40), font, fontScale=font_scale,color=(0,255,0), thickness=3)
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.show()
The ssd_mobilenet_v3_large_coco_2020_01_14.pbtxt link: https://gist.github.com/dkurt/54a8e8b51beb3bd3f770b79e56927bd7
Coco names link: https://github.com/pjreddie/darknet/blob/master/data/coco.names
frozen_inference_graph.pb link: https://drive.google.com/file/d/19seKEz-HYBkY_4DZV9ieu4gxgOnPxqhs/view

How do I embed Plotly charts exported as HTML in Powerpoint?

I am aware of adding URL to PPT, but due to certain privacy issues that cannot be done.
Is there any other way to import plotly charts to ppt? or any equivalent open source app that can be used?
Thank you in advance!
it's pretty straight forward to save as a static image https://plotly.com/python/static-image-export/
create a powerpoint https://python-pptx.readthedocs.io/en/latest/user/quickstart.html#
I don't have powerpoint or a Windows o/s. It's not clear that powerpoint works with active HTML
import plotly.express as px
import pandas as pd
import numpy as np
from pathlib import Path
df = pd.DataFrame({
"time": pd.date_range("1-Jul-2021", periods=200, freq="1H"),
"desired_light": np.random.choice(["ON", "OFF"], 200),
})
# build a figure
fig = px.bar(df, x="time", color="desired_light", height=400, title="Restaurant bills")
# export fingure as a static file: https://plotly.com/python/static-image-export/
fname = Path.cwd().joinpath("SO.png")
fig.write_image(fname)
# create a powerpoint from an image: https://python-pptx.readthedocs.io/en/latest/user/quickstart.html
from pptx import Presentation
from pptx.util import Inches
prs = Presentation()
blank_slide_layout = prs.slide_layouts[6]
slide = prs.slides.add_slide(blank_slide_layout)
left = top = Inches(1)
pic = slide.shapes.add_picture(str(fname), left, top)
prs.save(Path.cwd().joinpath('SO.pptx'))

Invalid pointer error whily running python in C++ using pybind11 and pytorch

While running the following python code in C++ using pybind11, pytorch 1.6.0, I get "Invalid Pointer" error. In python, the code runs successfully without any error. Whats the reason? How can I solve this problem?
import torch
import torch.nn.functional as F
import numpy as np
import cv2
import torchvision
import eval_widerface
import torchvision_model
def resize(image, size):
image = F.interpolate(image.unsqueeze(0), size=size, mode="nearest").squeeze(0)
return image
# define constants
model_path = '/path/to/model.pt'
image_path = '/path/to/image_pad.jpg'
scale = 1.0 #Image resize scale (2 for half size)
font = cv2.FONT_HERSHEY_SIMPLEX
MIN_SCORE = 0.9
image_bgr = cv2.imread(image_path)
image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)#skimage.io.imread(args.image_path)
cv2.imshow("input image",image_bgr)
cv2.waitKey()
cv2.destroyAllWindows()
# load pre-trained model
return_layers = {'layer2':1,'layer3':2,'layer4':3}
RetinaFace = torchvision_model.create_retinaface(return_layers)
print('RetinaFace.state_dict().')
retina_dict = RetinaFace.state_dict()
the following function generates error.
def create_retinaface(return_layers,backbone_name='resnet50',anchors_num=3,pretrained=True):
print('In create_retinaface.')
print(resnet.__dict__)
backbone = resnet.__dict__[backbone_name](pretrained=pretrained)
print('backbone.')
# freeze layer1
for name, parameter in backbone.named_parameters():
print('freeze layer 1.');
# if 'layer2' not in name and 'layer3' not in name and 'layer4' not in name:
# parameter.requires_grad_(False)
if name == 'conv1.weight':
# print('freeze first conv layer...')
parameter.requires_grad_(False)
model = RetinaFace(backbone,return_layers,anchor_nums=3)
return model
The statement backbone = resnet.__dict__ [backbone_name](pretrained=pretrained) generated error that looks like
*** Error in `./p': munmap_chunk(): invalid pointer: 0x00007f4461866db0 ***
======= Backtrace: =========
/usr/lib64/libc.so.6(+0x7f3e4)[0x7f44736b43e4]
/usr/local/lib64/libopencv_gapi.so.4.1(_ZNSt10_HashtableISsSsSaISsENSt8__detail9_IdentityESt8equal_toISsESt4hashISsENS1_18_Mod_range_hashingENS1_20_Default_ranged_hashENS1_20_Prime_rehash_policyENS1_17_Hashtable_traitsILb1ELb1ELb1EEEE21_M_insert_unique_nodeEmmPNS1_10_Hash_nodeISsLb1EEE+0xc9)[0x7f4483dee1a9]
/home/20face/.virtualenvs/torch/lib64/python3.6/site-packages/torch/lib/libtorch_python.so(+0x4403b5)[0x7f4460bb73b5]
/home/20face/.virtualenvs/torch/lib64/python3.6/site-packages/torch/lib/libtorch_python.so(+0x44570a)[0x7f4460bbc70a]
/home/20face/.virtualenvs/torch/lib64/python3.6/site-packages/torch/lib/libtorch_python.so(+0x275b20)[0x7f44609ecb20]
/usr/lib64/libpython3.6m.so.1.0(_PyCFunction_FastCallDict+0x147)[0x7f4474307167]
/usr/lib64/libpython3.6m.so.1.0(+0x1507df)[0x7f44743727df]
/usr/lib64/libpython3.6m.so.1.0(_PyEval_EvalFrameDefault+0x3a7)[0x7f44743670f7]
/usr/lib64/libpython3.6m.so.1.0(+0x1505ca)[0x7f44743725ca]
/usr/lib64/libpython3.6m.so.1.0(+0x150903)[0x7f4474372903]
/usr/lib64/libpython3.6m.so.1.0(_PyEval_EvalFrameDefault+0x3a7)[0x7f44743670f7]
/usr/lib64/libpython3.6m.so.1.0(+0x14fb69)[0x7f4474371b69]
/usr/lib64/libpython3.6m.so.1.0(_PyFunction_FastCallDict+0x24f)[0x7f44743739ff]
/usr/lib64/libpython3.6m.so.1.0(_PyObject_FastCallDict+0x10e)[0x7f44742ca1de]
/usr/lib64/libpython3.6m.so.1.0(_PyObject_Call_Prepend+0x61)[0x7f44742ca2f1]
/usr/lib64/libpython3.6m.so.1.0(PyObject_Call+0x43)[0x7f44742c9f63]
/usr/lib64/libpython3.6m.so.1.0(+0xfa7e5)[0x7f447431c7e5]
/usr/lib64/libpython3.6m.so.1.0(+0xf71e2)[0x7f44743191e2]
/usr/lib64/libpython3.6m.so.1.0(PyObject_Call+0x43)[0x7f44742c9f63]
/usr/lib64/libpython3.6m.so.1.0(_PyEval_EvalFrameDefault+0x2067)[0x7f4474368db7]
/usr/lib64/libpython3.6m.so.1.0(PyEval_EvalCodeEx+0x24f)[0x7f4474372c9f]
This line is causing the error because it assumes __dict__ has a backbone_name element:
backbone = resnet.__dict__[backbone_name](pretrained=pretrained)
When that isn't the case, it basically tries to access invalid memory. Check __dict__ first with an if statement or make sure that it has the backbone_name element before trying to use it.

How to remove the blank text boxes from python pptx generated slides?

from pptx import Presentation
from pptx.util import Inches
prs = Presentation("my_pptfile_begin.pptx")
left = Inches(0.6)
top = Inches(1.7)
blank_slide_1 = prs.slide_layouts[6]
add_the_slide = prs.slides.add_slide(blank_slide_1)
img_path1 = 'Three_Part_Set_Difference_excel_printout.png'
slide1=prs.slides[1]
pic = slide1.shapes.add_picture(img_path1, left, top)
blank_slide_2 = prs.slide_layouts[6]
add_the_slide = prs.slides.add_slide(blank_slide_2)
img_path2 = 'my_image.png'
slide2=prs.slides[2]
pic = slide2.shapes.add_picture(img_path2, left, top)
logoleft = Inches(4.7)
logotop = Inches(1.8)
blank_slide_3 = prs.slide_layouts[6]
add_the_slide = prs.slides.add_slide(blank_slide_3)
img_path3 = 'logo_slide.png'
slide3=prs.slides[3]
pic = slide3.shapes.add_picture(img_path3, logoleft, logotop)
prs.save('my_pptfile_Final.pptx')
How to remove the blank text boxes (or as a matter of fact all textboxes)?
I do not need any text boxes in my Powerpoint output file
If you're talking about empty placeholder shapes, just use a slide layout that has no placeholders.
In the default template used when you call Presentation() by itself (without an argument), that is the seventh layout I believe (prs.slide_layouts[6]).
But you need to adjust that for whatever starting .pptx file you're using ("my_pptfile_begin.pptx" in your case) by looking at it in slide-master view and counting down to the blank layout (or adding one if it doesn't have one).
blank_slide_3 = prs.slide_layouts[x] where x the slide number of the default template of your pptx application or your company's default template.
Therefore you need to know the default template and know the blank slide with no textboxes of that template based on the defaults of your ppt application

Color tables cells in ppt using python

So I have a excel which contains a table like this:
I want to get the same table in powerpoint using Python
Work Done till now:
Read the excel to python and store in pandas df
Add df to powerpoint
Code for the same effort:
from pd2ppt import df_to_table
import pandas as pd
from pptx import Presentation
from pptx.util import Inches
path =r"Sample PPT.pptx"
prs = Presentation(path)
title_slide_layout = prs.slide_layouts[5]
slide = prs.slides.add_slide(title_slide_layout)
title = slide.shapes.title
title.text = "Summary Table"
top = Inches(1.5)
left =Inches(0.25)
width =Inches(9.25)
height= Inches(5.0)
df_to_table(slide, df,left, top, width, height)
All I need is how to do color formatting in this table using Python?
Each cell in a PowerPoint table has its own fill, which can do everything other FillFormat objects can do::
from pptx.dml.color import RGBColor
cell = table.cell(0, 0) # ---or whatever cell you choose---
fill = cell.fill
fill.solid()
fill.fore_color.rgb = RGBColor(0xFA, 0x00, 0x37)
The FillFormat object interface is further described in the documentation here:
https://python-pptx.readthedocs.io/en/latest/api/dml.html#fillformat-objects

Categories