Graphviz not displaying PNG in Python Idle - ipython

I am using the following code to display in image in Python IDLE but no luck.
import pydot
import graphviz
import os
G = pydot.Dot(graph_type = 'digraph')
node = pydot.Node('Name')
G.add_node(node)
from IPython.display import Image, display
im = Image(G.create_png())
display(im)
Each time I run the code, it returns the following instead of displaying a png.
<IPython.core.display.Image object>
Could someone point out whats wrong here?
Thank you.

Related

Audio widget within Jupyter notebook is **not** playing. How can I get the widget to play the audio?

I writing my code within a Jupyter notebook in VS Code. I am hoping to play some of the audio within my data set. However, when I execute the cell, the console reports no errors, produces the widget, but the widget displays 0:00 / 0:00 (see below), indicating there is no sound to play.
Below, I have listed two ways to reproduce the error.
I have acquired data from the hub data store. Looking specifically at the spoken MNIST data set, I cannot get the data from the audio tensor to play
import hub
from IPython.display import display, Audio
from ipywidgets import interactive
# Obtain the data using the hub module
ds = hub.load("hub://activeloop/spoken_mnist")
# Create widget
sample = ds.audio[0].numpy()
display(Audio(data=sample, rate = 8000, autoplay=True))
The second example is a test (copied from another post) that I ran to see if it was something wrong with the data or something wrong with my console, environment, etc.
# Same imports as shown above
# Toy Function to play beats in notebook
def beat_freq(f1=220.0, f2=224.0):
max_time = 5
rate = 8000
times = np.linspace(0,max_time,rate*max_time)
signal = np.sin(2*np.pi*f1*times) + np.sin(2*np.pi*f2*times)
display(Audio(data=signal, rate=rate))
return signal
v = interactive(beat_freq, f1=(200.0,300.0), f2=(200.0,300.0))
display(v)
I believe that if it is something wrong with the data (this is a well-known data set so, I doubt it), then only the second one will play. If it is something to do with the IDE or something else, then neither will work, as is the case now.
Apologies for the late reply! In the future, please tag the questions with activeloop so it's easier to sort through (or hit us up directly in community slack -> slack.activeloop.ai).
Regarding the Free Spoken Digit Dataset, I managed to track the error with your usage of activeloop hub and audio display.
adding [:,0] to 9th line will help fixing display on Colab as Audio expects one-dimensional data
%matplotlib inline
import hub
from IPython.display import display, Audio
from ipywidgets import interactive
# Obtain the data using the hub module
ds = hub.load("hub://activeloop/spoken_mnist")
# Create widget
sample = ds.audio[0].numpy()[:,0]
display(Audio(data=sample, rate = 8000, autoplay=True))
(When we uploaded the dataset, we decided to upload the audio as (N,C) where C is the number of channels, which happens to be 1 for the particular dataset. The added dimension wasn't added automatically)
Regarding the VScode... the audio, unfortunately, would still not work (not because of us, but VScode), but you can still try visualizing Free Spoken Digit Dataset (you can play the music there, too). Hopefully this addresses your needs!
Let us know if you have further questions.
Mikayel from Activeloop

Why is this rdkit script not working in visual studio code?

I've been using VS code via jupyter notebook.
So, I have to produce grid image of 15 molecules and save it to my computer, but the script I've been using is not showing any errors, but still doesn't produce any images nor save them to designated file to my computer even though the cell gas been executed successfully.
I'm fresh and new to the world of computational chemistry and would appreciate any help!
My script is below.
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem.Draw import MolsToGridImage
from rdkit.Chem import SDMolSupplier
suppl = Chem.SDMolSupplier('chemspidersdf/database.sdf')
ms = [x for x in suppl if x is not None]
for m in ms: tmp=AllChem.Compute2DCoords(m)
img=Draw.MolsToGridImage(ms[:15],molsPerRow=5,subImgSize=(200,200),legends=[x.GetProp("_Name") for x in ms[:15]])
img.save('gridpng/test_molgrid.o.png')
Because you are using Jupyter the output of MolsToGridImage is likely not what you expect. In Jupyter the function returns an IPython.core.display.Image. You can save this to a png like so:
img = Draw.MolsToGridImage(mymols)
with open('molgrid.png', 'wb') as png:
png.write(img.data)
When run in a standard interpreter the function returns a PIL.PngImagePlugin.PngImageFile.
You could also return to the original behaviour (outside of jupyter) by uninstalling the IPython renderer although this would remove the nice behaviour of being able to see your molecule images displayed in the notebook.
from rdkit.Chem.Draw import IPythonConsole
IPythonConsole.UninstallIPythonRenderer()
img = Draw.MolsToGridImage(mymols)
img.save('molgrid.png')

icon_path isn't working in win10toast module in python

I'm attempting a countdown clock in python 3.7 using win10toast, time and playsound. Here's the code:
import time
import playsound
import win10toast
Toaster = win10toast.ToastNotifier()
def countdown(y):
while y > 0:
print(y)
y -= 1
time.sleep(1)
playsound.playsound('alarm-clock-ringing.mp3')
Toaster.show_toast('Countdown notifier', 'countdown over', duration=9,
icon_path=r'D:\img.ico')
try:
x = int(input('how many seconds do you want to countdown?: '))
countdown(x)
except ValueError:
print('That wasn\'t an integer! Please enter an integer!')
It works fine, except for icon_path in line 14. The error I'm getting is:
ERROR:root:Some trouble with the icon (D:\img.ico): (0, 'LoadImage', 'No error message is available')
By the way, I'm using windows 10 pro 64-bit.
Thank you!
Hello!
import time
from win10toast import ToastNotifier
toaster = ToastNotifier()
toaster.show_toast("Hello World!!!","Python is 10 seconds awsm!",icon_path=
filename.ico,duration=10,threaded=False)
while toaster.notification_active():
time.sleep(0.1)
Copy and Paste,
Your Welcome :)
First, convert the .jpg or .png file that u have into a .ico file. U can do it using python's PIL library like this:
from PIL import Image
filename = "logo.png"
img = Image.open(filename)
img.save('logo.ico')
Now, u have saved the logo as an ico file, so u can easily use it in ur code like this:
from win10toast import ToastNotifier
toast = ToastNotifier()
file_name = 'logo.ico'
toast.show_toast("Notification","Notification Body", duration=5, icon_path = file_name)
Hope that this helps!
According to the documentation, LOAD-ICON should pick up the 32x32 version of the icon (if it exists)
LOAD-IMAGE does not work if .ICO file contains a 256x256 icon.
Using an ICO file with 32x32, 16x16, and/or 48x48 icons works.
Icon files with several images work unless it contains a 256x256 version. In this case, no icon is loaded.
for reference click here
just replace this:
'D:\img.ico' ==> 'D:/img.ico'
or use it in this way:
'D:\\img.ico'
Try using a .ico file, that would probably work..

cvlib detect_common_objects is not working

https://github.com/arunponnusamy/cvlib/tree/f46a22f8e13bc4b0267b9057fa88de170d41f96a
I'm checking examples of cvlib and trying on my own on spyder Python 3.7
Face detection is working very fine..
Gender detection working very fine but object detection is not working...
Output is the image itself.
I have tried BGR2RGB but nothing happens.
here is code
import cvlib as cv
from cvlib.object_detection import draw_bbox
import cv2
path = r'C:\Users\user\desktop\cod\object_detection_input.jpg'
image = cv2.imread(path)
bbox, label, conf = cv.detect_common_objects(image)
print(bbox, label, conf)
out = draw_bbox(image, bbox, label, conf)
cv2.imshow("object_detection", out)
cv2.waitKey()
cv2.destroyAllWindows()
If the function return empty list, the probable reason is problems in yolov3.cfg, yolov3.weights files that train the model (yolov3.weights is 242 mg file).
In windows these files should be in folder:
C:\Users\USER_NAME\.cvlib\object_detection\yolo\yolov3
The files are download in the first time the function work. If the files are corrupted, the function will not work but also will not throw an error!!
fix: Delete these files and run the function again you will see download of both files.
I Guess the problem about kernel restart after installation of libraries. When I restart computer. It worked.

PIL to Qimage conversion: QImage constructor does not free memory

I am developping a Qt application loading pictures with PIL, modifying colors and alpha channels, then converting them as QImage.
Here is the problematic piece of code: normal repeated usage of the ImageQt function: # memory is filled around 7 mB/s
if name == 'main':
while True:
im = Image.open('einstein.png') #small picture
imQt = QtGui.QImage(ImageQt.ImageQt(im)) # convert to PySide.QtGui.QImage
imQt.save('outtest.png')# -> rendered picture is correct
#del(imQt) and del(im) does not change anything
time.sleep(0.02)
The problem here is the crazy memory filling, when the picture is supposed to be erased by the garbage collector. I checked with gc.collect(), but it did not change anything.
This example shows what happends with the imageQt function, but in fact, I noticed this is a problem caused by QImage: if you repeatedly use the QImage constructor with data, the memory used by python process increases: im= Image.load('mypic.png').convert('RGBA')
data = im.toString('raw','RGBA')
qIm = QtGui.QImage(data,im.size[0],im.size[1],QtGui.QImage.Format_ARGB32)
qIm.save('myConvertedPic.png')# -> picture is perfect
If you put this code in a loop, memory will increase, as 1st example. From there i am a bit lost because this is a PySide problem...
I tried to use a workaround, but it does not work either:
#Workaround, but not working ....
if name == 'main':
while True:
im = Image.open('einstein.png') #small picture
imRGBA = im.convert('RGBA') # convert to RGBA
imRGBA.save('convtest.png') # ->picture is looks perfect
imBytes = imRGBA.tostring('raw','RGBA')
#print("size %d %d" % (imRGBA.size[0],imRGBA.size[1]))
qImage = QtGui.QImage(imRGBA.size[0],imRGBA.size[1],QtGui.QImage.Format_ARGB32) # create new empty picture
qImage.fill(QtCore.Qt.blue) # fill with blue, otherwise it catches pieces of the picture still in memory
loaded = qImage.loadFromData(imBytes,'RGBA') # load from raw data
print("success %d" % loaded)# -> returns 0
qImage.save('outtest.png')# -> rendered picture is blue
time.sleep(0.02)
I am really stuck here, if you could help find a solution with this workaround ? Because I'm really stuck here!
Also I would like to discuss the QImage problem. Is there any reliable way to free this memory ? Could the fact I am using python3.2(32bits) be a problem in this case ? Am I the only one in this case ?
The imports I am using in case of:
import time
import sys
import PySide
sys.modules['PyQt4'] = PySide # this little hack allows to solve naming problem when using PIL with Pyside (instead of PyQt4)
from PIL import Image, ImageQt
from PySide import QtCore,QtGui
After further unsuccessful searching, I noticed, that the PIL function image.tostring() associated with a QImage constructor caused this problem
im = Image.open('einstein.png').convert('RGBA')
data = im.tostring('raw','RGBA') # the tostring() function is out of the loop
while True:
imQt = QtGui.QImage(data,im.size[0],im.size[1],QtGui.QImage.Format_ARGB32)
#imQt.save("testpic.png") #image is valid
time.sleep(0.01)
#no memory problem !I think I am really close to find what is wrong, but I cannot point it out.
It definitely has something to do with the data variable being held in memory.