Can't import using * with - python

I have the following code:
https://github.com/marcomusy/vedo/blob/master/examples/basic/colorlines.py
"""Color lines by a scalar"""
from vedo import *
pts1 = [(sin(x/8), cos(x/8), x/5) for x in range(25)]
l1 = Line(pts1).c('black')
l2 = l1.clone().rotateZ(180).shift(1,0,0)
dist = mag(l1.points()-l2.points()) # make up some scalar values
# The trick here is to think that the "body" of a line is a cell
# so we can color cells as we do for any other polygonal mesh:
lines = Lines(l1, l2).lw(4).cmap('Accent', dist, on='cells')
lines.addScalarBar(title='distance') # or e.g.:
# lines.addScalarBar3D(title='distance').scalarbar.rotateX(90).pos(1,1,2)
show(l1,l2, lines, __doc__, axes=1, bg2='lightblue', viewup='z')
However, this gives me the following error:
Traceback (most recent call last):
File "vedo.py", line 2, in <module>
from vedo import *
File "/Users/prikshetsharma/Documents/clotorch/src/clotorch/flight/vedo.py", line 4, in <module>
pts1 = [(sin(x/8), cos(x/8), x/5) for x in range(25)]
File "/Users/prikshetsharma/Documents/clotorch/src/clotorch/flight/vedo.py", line 4, in <listcomp>
pts1 = [(sin(x/8), cos(x/8), x/5) for x in range(25)]
NameError: name 'sin' is not defined
However, sin is imported from numpy in the init.py file of vedo, so it should be defined in this file.

Related

matplotlib's contourf producing error in tikzplotlib

could someone point out to what is wrong with the following code?
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from matplotlib import cm,colors
import tikzplotlib
max_r = 20
N_vorfs = 500
scalings = np.linspace(0.1, 5.*np.pi, N_vorfs)
X, Y = np.meshgrid(scalings, 2.*np.arange(1, max_r+1)-1.)
Z = np.arange(max_r*N_vorfs).reshape(X.shape)
fig, axs = plt.subplots(2, 1, gridspec_kw={'height_ratios': [3, 1]})
axs[0].contour(X, Y, Z)
print(tikzplotlib.get_tikz_code())
plt.show()
I get errors from tikzplotlib, namely
Traceback (most recent call last):
File ".../to_pgfplot.py", line 19, in <module>
print(tikzplotlib.get_tikz_code())
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tikzplotlib/_save.py", line 209, in get_tikz_code
data, content = _recurse(data, figure)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tikzplotlib/_save.py", line 353, in _recurse
data, children_content = _recurse(data, child)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tikzplotlib/_save.py", line 378, in _recurse
data, cont = _draw_collection(data, child)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tikzplotlib/_save.py", line 319, in _draw_collection
return _path.draw_pathcollection(data, child)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tikzplotlib/_path.py", line 214, in draw_pathcollection
p = obj.get_paths()[0]
IndexError: list index out of range

Problems with Weasyprint: ModuleNotFoundError

I would like to display the text from an image and then have the coordinates determined for each word in the text. For this I use the following code:
from doctr.io import DocumentFile
from doctr.models import ocr_predictor
import json
import math
import PIL
from PIL import ImageDraw
import matplotlib.pyplot as plt
model = ocr_predictor (det_arch='db_resnet50', reco_arch='crnn_vgg16_bn',pretrained=True)
bildpfad = "C:/Users/b2/Documents/Analysetext_1.png"
bild = DocumentFile.from_images (bildpfad)
ergebnis = model (bild)
output = ergebnis.export ()
with open ("C:/Users/b2/Documents/docTR_OCR_output.json", "w") as f:
f.write (json.dumps (output, indent=1))
f.close ()
ergebnis.show (bild)
# Geometrische Koordinaten
for object_1 in output ['pages'] [0] ["blocks"]:
for object_2 in object_1 ["lines"]:
for object_3 in object_2 ["words"]:
print ("{}: {}".format (object_3 ["geometry"], object_3 ["value"]))
# Output like [x_min, x_max, y_min, y_max]
# Geographische Koordinaten
def convert_coordinates (geometry, page_dim):
len_x = page_dim[1]
len_y = page_dim[0]
(x_min, y_min) = geometry[0]
(x_max, y_max) = geometry[1]
x_min = math.floor(x_min * len_x)
x_max = math.ceil(x_max * len_x)
y_min = math.floor(y_min * len_y)
y_max = math.ceil(y_max * len_y)
return [x_min, x_max, y_min, y_max]
def get_coordinates (output):
page_dim = output ['pages'][0]["dimensions"]
text_coordinates = []
for object_1 in output ['pages'][0]["blocks"]:
for object_2 in object_1 ["lines"]:
for object_3 in object_2 ["words"]:
converted_coordinates = convert_coordinates (object_3 ["geometry"], page_dim)
print ("{}: {}".format (converted_coordinates, object_3 ["values"]))
text_coordinates.append (converted_coordinates)
return text_coordinates
graphical_coordinates = get_coordinates (output)
print (graphical_coordinates)
# Plot graphische Koordinaten
def draw_bounds(bild, bound):
draw = ImageDraw.Draw(bild)
for b in bound:
p0, p1, p2, p3 = [b[0],b[2]], [b[1],b[2]], \
[b[1],b[3]], [b[0],b[3]]
draw.line([*p0,*p1,*p2,*p3,*p0], fill='blue', width=2)
return bild
bild = PIL.Image.open(bildpfad)
result_image = draw_bounds(bild, graphical_coordinates)
plt.figure(figsize=(15,15))
plt.imshow(result_image)
At the beginning I had the following error:
OSError: cannot load library 'gobject-2.0-0': error 0x7e. Additionally, ctypes.util.find_library() did not manage to locate a library called 'gobject-2.0-0'
I was then able to fix this error and now the following is displayed:
ModuleNotFoundError: No module named 'weasyprint.text.ffi'; 'weasyprint.text' is not a package
The whole output is:
Traceback (most recent call last):
File "c:/Users/b2/Documents/Übungen/Distanzberechnungen/Textdetection_Übung_3.py", line 3, in <module>
from doctr.io import DocumentFile
File "C:\Users\b2\anaconda3\envs\Python_3_6\lib\site-packages\doctr\__init__.py", line 1, in <module>
from . import datasets, io, models, transforms, utils
File "C:\Users\b2\anaconda3\envs\Python_3_6\lib\site-packages\doctr\datasets\__init__.py", line 3, in <module>
from .generator import *
File "C:\Users\b2\anaconda3\envs\Python_3_6\lib\site-packages\doctr\datasets\generator\__init__.py", line 4, in <module>
from .tensorflow import *
File "C:\Users\b2\anaconda3\envs\Python_3_6\lib\site-packages\doctr\datasets\generator\tensorflow.py", line 8, in <module>
from .base import _CharacterGenerator, _WordGenerator
File "C:\Users\b2\anaconda3\envs\Python_3_6\lib\site-packages\doctr\datasets\generator\base.py", line 11, in <module>
from doctr.io.image import tensor_from_pil
File "C:\Users\b2\anaconda3\envs\Python_3_6\lib\site-packages\doctr\io\__init__.py", line 2, in <module>
from .html import *
File "C:\Users\b2\anaconda3\envs\Python_3_6\lib\site-packages\doctr\io\html.py", line 8, in <module>
from weasyprint import HTML
File "C:\Users\b2\anaconda3\envs\Python_3_6\lib\site-packages\weasyprint\__init__.py", line 315, in <module>
from .css import preprocess_stylesheet # noqa isort:skip
File "C:\Users\b2\anaconda3\envs\Python_3_6\lib\site-packages\weasyprint\css\__init__.py", line 25, in <module>
from . import computed_values, counters, media_queries
File "C:\Users\b2\anaconda3\envs\Python_3_6\lib\site-packages\weasyprint\css\computed_values.py", line 9, in <module>
from ..text.ffi import ffi, pango, units_to_double
ModuleNotFoundError: No module named 'weasyprint.text.ffi'; 'weasyprint.text' is not a package
I hope you can help me to fix this error. Thank you in advance

bbox works when inputting exact coordinates within module but fails with variable containing identical data

I'm having an issue trying to make a screen grab of an area defined by lines in a config file:
The following code:
def coordstore(): # check line 1 of config file (screencap name)
f=open('config.txt')
line=f.readlines()
coordstore.x1,coordstore.y1,coordstore.x2,coordstore.y2 = (line[4]).strip(),(line[5]).strip(),(line[6]).strip(),(line[7]).strip() # note: confusing. 0=line 1, 1=line2 etc.
coordstore.coords = coordstore.x1+',',coordstore.y1+',',coordstore.x2+',',coordstore.y2
coordstore.stripped = ' '.join((coordstore.coords))
print(coordstore.stripped)
return(coordstore.stripped)
coordstore()
def screenshot():
import pyscreenshot as ImageGrab2
# part of the screen
if __name__ == '__main__':
im = ImageGrab2.grab(bbox=(coordstore.stripped)) # X1,Y1,X2,Y2
im.save('tc.png')
screenshot()
prints exactly this value: 10, 20, 100, 300
it then fails with this Traceback:
Traceback (most recent call last):
File "file location", line 82, in <module>
screenshot()
File "file location", line 80, in screenshot
im = ImageGrab2.grab(bbox=(coordstore.stripped)) # X1,Y1,X2,Y2
File "PYCHARM\venv\lib\site-packages\pyscreenshot\__init__.py", line 67, in grab
to_file=False, childprocess=childprocess, backend=backend, bbox=bbox)
File "PYCHARM\venv\lib\site-packages\pyscreenshot\__init__.py", line 38, in _grab
x1, y1, x2, y2 = bbox
ValueError: too many values to unpack (expected 4)
If I manually replace (bbox=(coordstore.stripped)) with (bbox=(10, 20, 100, 300)) which is literally identical to what the variable prints, the code works perfectly but is not useful for my needs. What am I not seeing? Thanks for the help!
UPDATE:
I have tried another approach.
def coordstore(): # check line 1 of config file (screencap name)
f=open('config.txt')
line=f.readlines()
coordstore.x1 = (line[4]).strip()
coordstore.y1 = (line[5]).strip()
coordstore.x2 = (line[6]).strip()
coordstore.y2 = (line[7]).strip()
print(coordstore.x1+',', coordstore.y1+',', coordstore.x2+',', coordstore.y2)
return(coordstore.x1, coordstore.y1, coordstore.x2, coordstore.y2)
coordstore()
def screenshot():
import pyscreenshot as ImageGrab2
# part of the screen
if __name__ == '__main__':
im = ImageGrab2.grab(bbox=(coordstore.x1+',', coordstore.y1+',', coordstore.x2+',', coordstore.y2+',')) # X1,Y1,X2,Y2
im.save('tc.png')
screenshot()
This prints
10, 20, 100, 300
but returns the following Traceback errors:
Traceback (most recent call last):
File "module location", line 84, in <module>
screenshot()
File "module location", line 82, in screenshot
im = ImageGrab2.grab(bbox=(coordstore.x1+',', coordstore.y1+',', coordstore.x2+',', coordstore.y2+',')) # X1,Y1,X2,Y2
File "\PYCHARM\venv\lib\site-packages\pyscreenshot\__init__.py", line 67, in grab
to_file=False, childprocess=childprocess, backend=backend, bbox=bbox)
File "\PYCHARM\venv\lib\site-packages\pyscreenshot\__init__.py", line 42, in _grab
raise ValueError('bbox y2<=y1')
ValueError: bbox y2<=y1
As you have mentioned in comments the value of coordstore.stripped is string. And expected argument by ImageGrab2.grab is type of tuple so, first you have to convert it into tuple.
Update the method like this:
def screenshot():
import pyscreenshot as ImageGrab2
# part of the screen
if __name__ == '__main__':
im = ImageGrab2.grab(bbox=tuple(map(int, coordstore.stripped.split(', ')))) # X1,Y1,X2,Y2
im.save('tc.png')

Converting a list to a sequence to make a sympy Polygon

I would like to make a sympy Polygon from a list of points. The documentation says it takes a sequence of Points. I can't figure out how to convert.
from sympy import Point2D, Polygon
# this works
p1 = Polygon(Point2D(0,0), Point2D(1,0), Point2D(1,1), Point2D(0,1))
print(p1.area)
# this fails at the Polygon call
points=[]
points.append(Point2D(0,0))
points.append(Point2D(0,1))
points.append(Point2D(1,1))
points.append(Point2D(1,0))
t = tuple(points)
p = Polygon(t)
When it fails, I get this
Traceback (most recent call last):
File "t_polygon.py", line 14, in <module>
p = Polygon(t)
File "C:\Program Files (x86)\Python\Lib\site-packages\sympy\geometry\polygon.py", line 126, in __new__
vertices = [Point(a, dim=2, **kwargs) for a in args]
File "C:\Program Files (x86)\Python\Lib\site-packages\sympy\geometry\polygon.py", line 126, in <listcomp>
vertices = [Point(a, dim=2, **kwargs) for a in args]
File "C:\Program Files (x86)\Python\Lib\site-packages\sympy\geometry\point.py", line 157, in __new__
raise ValueError('Nonzero coordinates cannot be removed.')
ValueError: Nonzero coordinates cannot be removed.
Instead of this:
t = tuple(points)
p = Polygon(t)
You need to write:
t = tuple(points)
p = Polygon(*t)

What should I do for using theano scan in deep Learning

I want to use then scan for a tensor3 calculation in my DNN, we can say this tensor3 is a 3D matrix, I want each layer of this matrix go through the T.nnet.softmax(T.dot(v, W)+b) calculation, the W, and b should be the fixed, so I could do the update for later. The following is my coding:
XS = T.tensor3("XS")
W = T.matrix(name="W")
b = T.vector(name="b")
results, updates = theano.scan(lambda XS: T.nnet.softmax(T.dot(XS,W) + b),
sequences=[XS],
outputs_info=None)
result = results
Mutiply = theano.function(inputs=[XS, W, b], outputs=[result])
#initialization of output of layer2
w_o = init_weights((1089, 10))
b_o = init_weights((10,))
myFile_data = h5py.File('/Users/XIN/Masterthesis/Torch_Script/mnist-cluttered/train_data.h5', 'r')
myFile_label= h5py.File('/Users/XIN/Masterthesis/Torch_Script/mnist-cluttered/train_target.h5', 'r')
data = myFile_data['data'][...]
label = myFile_label['target'][...]
data = data.reshape(100000, 10000)
trX = data
trY = label
X_s = downsampling(trX)
X_nine = load_data_train(trX, trX.shape[0], 9)
X_nine = X_nine.transpose((((2,0,1))))
p_x_nine = Mutiply(X_nine, w_o, b_o)[0]
but the results show this error:
runfile('/Users/XIN/Masterthesis/keras/thean_scan_test.py', wdir='/Users/XIN/Masterthesis/keras')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/XIN/anaconda/lib/python2.7/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 699, in runfile
execfile(filename, namespace)
File "/Users/XIN/anaconda/lib/python2.7/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 81, in execfile
builtins.execfile(filename, *where)
File "/Users/XIN/Masterthesis/keras/thean_scan_test.py", line 115, in <module>
p_x_nine = Mutiply(X_nine, w_o, b_o)[0]
File "/Users/XIN/anaconda/lib/python2.7/site-packages/theano/compile/function_module.py", line 786, in __call__
allow_downcast=s.allow_downcast)
File "/Users/XIN/anaconda/lib/python2.7/site-packages/theano/tensor/type.py", line 86, in filter
'Expected an array-like object, but found a Variable: '
TypeError: ('Bad input argument to theano function with name "/Users/XIN/Masterthesis/keras/thean_scan_test.py:92" at index 1(0-based)', 'Expected an array-like object, but found a Variable: maybe you are trying to call a function on a (possibly shared) variable instead of a numeric array?')
I check the X_nine type is: np array but the w_o, and b_o is theano type.
So what should I do to modify this code.
get the solution by my mentor, coding it like following:
XS = T.tensor3("XS")
w_o = init_weights((1089, 10))
b_o = init_weights((10,))
results, updates = theano.scan(lambda XS: T.nnet.softmax(T.dot(XS,w_o) + b_o),
sequences=[XS],
outputs_info=None)
result = results
Mutiply = theano.function(inputs=[XS], outputs=[result])

Categories

Resources