I am using matplotlib with mpld3 library to draw a graph in django, but when I am creating a simple bar graph with the following code:
x=np.arange(2014, date.today().year+1, 1)
my_xticks = list(x)
educationData=np.array(getDatas(x, eType=[3, 4, 5]))
figEdu = plt.figure()
axE = figEdu.add_subplot(111)
plt.xticks(x, my_xticks)
plt.xlabel('Year')
plt.ylabel('#Participants')
plt.text(0.2, 0.9, '#Participants: '+str(np.sum(educationData)), ha='center', va='center', transform=axE.transAxes, fontsize=18, color='#009EF3', weight='bold')##00b3fe
plt.bar(x, educationData, color=['#009EF3'])
figHtmlEdu = mpld3.fig_to_html(figEdu)
plt.close()
figAwr = plt.figure()
axA = figEdu.add_subplot(111)
awarenessData=np.array(getDatas(x, eType=[1]))
plt.xticks(x, my_xticks)
plt.xlabel('Year')
plt.ylabel('#Participants')
plt.text(0.2, 0.9, '#Participants: '+str(np.sum(awarenessData)), ha='center', va='center', transform=axA.transAxes, fontsize=18, color='#FFAF27', weight='bold')##00a65a
plt.bar(x, awarenessData, color=['#FFAF27'])
figHtmlAwr = mpld3.fig_to_html(figAwr)
plt.close()
figTrn = plt.figure()
axT = figEdu.add_subplot(111)
trainingData=np.array(getDatas(x, eType=[2]))
plt.xticks(x, my_xticks)
plt.xlabel('Year')
plt.ylabel('#Participants')
plt.text(0.2, 0.9, '#Participants: '+str(np.sum(trainingData)), ha='center', va='center', transform=axT.transAxes, fontsize=18, color='#00E18C', weight='bold')##ffad00
plt.bar(x, trainingData, color=['#00E18C'])
figHtmlTrn = mpld3.fig_to_html(figTrn)
plt.close()
It's running fine for the first time but on refresh it's giving
RuntimeError: main thread is not in main loop
Tcl_AsyncDelete: async handler deleted by the wrong thread
So please help me with this exception.
Related
From the MSCOCO dataset segmentation annotations, how can I extract just the segmented objects themselves? For example, given an image of a person standing with a house in the background, how can I extract just the person themselves?
If your data is already in FiftyOne, then you can write a simple function using OpenCV and Numpy to crop the segmentations in your FiftyOne labels. It could look something like this:
import os
import cv2
import numpy as np
import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F
def extract_classwise_instances(samples, output_dir, label_field, ext=".png"):
print("Extracted object instances...")
for sample in samples.iter_samples(progress=True):
img = cv2.imread(sample.filepath)
img_h,img_w,c = img.shape
for det in sample[label_field].detections:
mask = det.mask
[x,y,w,h] = det.bounding_box
x = int(x * img_w)
y = int(y * img_h)
h, w = mask.shape
mask_img = img[y:y+h, x:x+w, :]
alpha = mask.astype(np.uint8)*255
alpha = np.expand_dims(alpha, 2)
mask_img = np.concatenate((mask_img, alpha), axis=2)
label = det.label
label_dir = os.path.join(output_dir, label)
if not os.path.exists(label_dir):
os.mkdir(label_dir)
output_filepath = os.path.join(label_dir, det.id+ext)
cv2.imwrite(output_filepath, mask_img)
label_field = "ground_truth"
classes = ["person"]
dataset = foz.load_zoo_dataset(
"coco-2017",
split="validation",
label_types=["segmentations"],
classes=classes,
max_samples=20,
label_field=label_field,
dataset_name=fo.get_default_dataset_name(),
)
view = dataset.filter_labels(label_field, F("label").is_in(classes))
output_dir = "/tmp/coco-segmentations"
os.makedirs(output_dir, exist_ok=True)
extract_classwise_instances(view, output_dir, label_field)
as for some background, my code is most likely a complete mess, mostly since I've only had a couple of hours scripting in my life.
For class im creating a solar system with all the standard planets and also the option for the user to input their own planet. Everything worked fine up until i tried letting the user spawn the planets with a button in the UI(an ugly button for now but a button nonetheless). If the user presses a button, say 'Sun', then the sun spawns, but only once, if he then decides to spawn sun again or any other planet for that matter, it gives an error stating that the module doesn't contain 'polycube or polysphere'. So basically, the button works once, then doesn't work anymore. If i call them from anywhere but the button, it works perfectly and indefinitely. I figured since he doesn't know polycube or polysphere, its almost as if i didn't import maya.cmds, so lets try recalling it. and low and behold that works.
So basically my question is as follows, does maya forget its imported libraries when you press a button? and How do i solve this without having to re-import maya.cmds in every function?
import maya.cmds as maya
class create_body:
def __init__(self, distance, radius, bonus_scale, r, g, b):
import maya.cmds as maya
self.radius = radius * bonus_scale / 1000
self.bonusScale = bonus_scale
self.distanceScene = distance
self.distanceMeter = distance*1000000000
maya.polyCube()
self.r = r
self.g = g
self.b = b
def color_body_custom(self):
import maya.cmds as maya
value = maya.colorEditor()
self.color = [float(i) for i in value.split()]
self.r = self.color[0]
self.g = self.color[1]
self.b = self.color[2]
def spawn_body(self):
import maya.cmds as maya
maya.polySphere(r = self.radius)
maya.move(self.distanceScene, moveZ = True)
maya.move(0, 0, 0, ".scalePivot", ".rotatePivot", absolute=True)
maya.polyColorPerVertex(rgb=(self.r,self.g,self.b), colorDisplayOption=True)
def animate_body(self):
import maya.cmds as maya
orbitTimeYears = self.get_orbital_time()*10
key = str(orbitTimeYears) + 'sec'
maya.setKeyframe(v=0, at='rotateY', t=['0sec'], itt = 'spline', ott = 'spline')
maya.setKeyframe(v=-360, at='rotateY', t=[key], itt = 'spline', ott = 'spline')
maya.selectKey(attribute='rotateY')
maya.setInfinity(pri='linear', poi='linear')
def get_orbital_time(self):
import math
orbitMeter = self.distanceMeter * 2 * math.pi
gravConst = 132690600000000000000 / self.distanceMeter
orbitSpeed = math.sqrt(gravConst)
orbitTimeSec = orbitMeter / orbitSpeed
orbitTimeYears = orbitTimeSec / 31556926
return orbitTimeYears
class create_ui:
def __init__(self, window_name):
self.myPlanetarySystem = window_name
# Make sure there's only one window open by deleting the window if it exists
self.delete_ui()
# Create the UI
self.myp = maya.window(self.myPlanetarySystem)
maya.rowColumnLayout(numberOfColumns=3, columnWidth=[(1, 150), (2, 75), (3, 75)], columnOffset=[(1, 'left', 5)])
maya.showWindow()
maya.window(self.myPlanetarySystem, e=True, title='TileGenerator', w=200, h=190)
maya.button(label = 'Sun', command = partial(self.body, 0, 695.510, 10, True, 1, 1, 0))
maya.button(label='Mercury', command = partial(self.body, 57.9, 2.439, 1000, False, 0.2, 0.2, 0))
#Sun = create_body(0, 695.510, 10, 1, 1, 0)
#Sun.spawn_body()
#Mercury = create_body(57.9, 2.439, 1000, 0.2, 0.2, 0)
#Mercury.spawn_body()
#Mercury.animate_body()
#Venus = create_body(108.2, 6.051, 1000, .5, 0.2, 0)
#Venus.spawn_body()
#Venus.animate_body()
#Earth = create_body(149.6, 6.971, 1000, 0, 0, 1)
#Earth.spawn_body()
#Earth.animate_body()
#Mars = create_body(227.9, 3.389, 1000, 0.6, 0.1, 0)
#Mars.spawn_body()
#Mars.animate_body()
#Jupiter = create_body(778.5, 69.911, 100, 0.9, 0.8, 0.5)
#Jupiter.spawn_body()
#Jupiter.animate_body()
#Saturn = create_body(1433.4, 58.232, 100, 0.8, 0.8, 0.7)
#Saturn.spawn_body()
#Saturn.animate_body()
#Uranus = create_body(2876.6, 25.362, 100, 0.7, 0.8, 1.0)
#Uranus.spawn_body()
#Uranus.animate_body()
#Neptune = create_body(4503.4, 24.622, 100, 0.3, 0.4, 0.7)
#Neptune.spawn_body()
#Neptune.animate_body()
def delete_ui(self):
if maya.window(self.myPlanetarySystem, exists=True):
maya.deleteUI(self.myPlanetarySystem, window=True)
def body(self, distance, radius, bonus_scale, is_sun, r = 0.5, g = 0.5, b = 0.5, *args):
obj = create_body(distance, radius, bonus_scale, r, g, b)
obj.spawn_body()
if not is_sun:
obj.animate_body()
create_ui('myPlanetarySystem')
Answer: apparently importing my maya.cmds in the shorter version: maya conflicted with the program, i should've seen this coming. In other words, there's no more issues if I just import maya.cmds as cmds.
I am trying to draw a legend under two plots (created using twinx). I want the legend to draw at the bottom center aligned with 4 columns. So far no success. How can I make the legend with respect to the entire plot, not just with a single axis object. Any help ?
import matplotlib.pyplot as plt;
import numpy as np;
from matplotlib import rc;
filename = 'ml.pdf';
fig, ax1 = plt.subplots(frameon=False);
rc('mathtext', default='regular');
rc('lines',lw=2.6);
rc('lines',mew=2.4);
rc('text', usetex=True);
x = np.array([5,10,20,50]);
dp_g = np.array([23.43, 29.93, 36.50, 46.07]);
mr_g = np.array([25.33, 31.83, 38.39, 47.75]);
md_g = np.array([24.94, 31.33, 37.80, 47.10]);
sb_g = np.array([27.01, 34.86, 43.18, 54.35]);
lns1 = ax1.plot(x,dp_g,'bs:', label="MD\n($\lambda$=.8)");
lns2 = ax1.plot(x,mr_g,'bs--',label="MR\n($\lambda$=.1)");
lns3 = ax1.plot(x,md_g,'bs-.',label='MD');
lns4 = ax1.plot(x,sb_g,'bs-',label="SB\n($\gamma$=.1)");
ax1.set_ylabel('CG ($\times$ 100)',color='b',size=14);
ax1.set_ylim([20,57]);
ax1.set_xlim([4,51]);
ax1.set_xticks(x);
ax1.tick_params(axis='y', which=u'both', length=0, labelsize=14, colors='b');
ax1.tick_params(axis='x', which=u'both', length=0, labelsize=14);
ax2 = ax1.twinx();
dp_d = np.array([18.84, 19.55, 20.09, 20.08]);
mr_d = np.array([19.42, 19.73, 20.06, 20.04]);
md_d = np.array([19.02, 19.75, 20.28, 20.29]);
sb_d = np.array([20.81, 19.77, 19.20, 19.03]);
lns6 = ax2.plot(x,dp_d,'rv:',label="MD\n($\lambda$=.8)");
lns7 = ax2.plot(x,mr_d,'rv--',label="MR\n($\lambda$=.1)");
lns8 = ax2.plot(x,md_d,'rv-.',label='MD');
lns9 = ax2.plot(x,sb_d,'rv-',label="SB\n($\gamma$=.1)");
lns = lns1 + lns2 + lns3 + lns4 + lns6 + lns7 + lns8 + lns9;
labs = [l.get_label() for l in lns];
ax2.set_ylabel('LD ($\times$ 100)',color='r',size=14);
ax2.set_ylim([15,23]);
ax2.set_xlim([4,51]);
ax2.set_xticks(x);
ax2.tick_params(axis='y', which=u'both', length=0, labelsize=14, colors='r');
ax2.tick_params(axis='x', which=u'both', length=0, labelsize=14);
ax1.set_xlabel('\# of items',size=14);
borderaxespad=2.5, ncol = 1, fontsize='11.5');
lgd = ax1.legend(lns, labs, bbox_to_anchor=(1.01,1.0), loc='lower center', borderaxespad=2.5, ncol = 4, fontsize='14');
fig.savefig(filename,format='pdf',transparent=True, bbox_extra_artists=(lgd,), bbox_inches='tight');
Apart from the broken line borderaxespad=2.5, ncol = 1, fontsize='11.5');, I believe what you want to do is to just remove the bbox_to_anchor=(1.01, 1.0) from the legend-definition. Doing so will put the legend at the bottom center of the plot (however the legend is very wide so it will span the entire width of the plot).
I just finished a work program to faces recognition using python on ubuntu system
But when you want to move the work to "Raspberry pi" gives this error
this is full error :
AttributeError: 'module' object has no attribute 'createLBPHFaceRecognizer'
What is the solution
Thank you
import cv2
import sys
import cv
import glob
import numpy as np
import os
labeltest=[]
Images=[]
Len=0
model = cv2.createLBPHFaceRecognizer(1,8,8,8,70.0)
Labels=[]
textsay=""
# *********** Read *****************\\
def read():
arr={}
with open("csv.ext") as f:
for line in f:
arr=line.split("%",2)
labeltest.append(arr[1])
Images.append(cv2.imread(arr[0],cv2.IMREAD_GRAYSCALE))
label=range(0,len(labeltest))
for i in range(0,len(labeltest)):
label[i]=int(labeltest[i])
print (label)
model.train(np.asarray(Images),np.asarray(label))
model.save("mezo.xml")
model.load("mezo.xml")
# //*********** Read *****************
def writetofile(key):
fo = open("csv.ext", "a+")
fo.write(key)
fo.write("\n")
def searchName(key):
lines=tuple(open("Names.txt","r"))
for i in range(0,len(lines)):
test=lines[i].split("\n")
print test[0]
if str(key.lower())==str(test[0].lower()):
return i
return -1
def readName():
lines=tuple(open("Names.txt","r"))
for i in range(0,len(lines)):
Labels.append(lines[i])
print Labels
def AddName(key):
fo = open("Names.txt", "a+")
fo.write(key)
fo.write("\n")
readName()
# *********** Add *****************\\
def Add(faces,gray):
count=Len+100
for (x, y, w, h) in faces:
filename = "/home/mohammad/Desktop/traning/%03d"%count +".pgm"
f=gray[y:y+h,x:x+w]
f=cv2.resize(f,(92,112),interpolation=cv2.INTER_LANCZOS4)
newName=raw_input("Enter the Name : ")
index=searchName(newName)
if index==-1:
index=len(Labels)
AddName(newName)
filenameIn = filename+"%"+str(index)
writetofile(filenameIn)
cv2.imwrite(filename,f)
count+=1
read()
# //*********** Add *****************
path={}
path=glob.glob("/home/mohammad/Desktop/traning/*.pgm")
Len=len(path)-1
cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
count=0
video_capture = cv2.VideoCapture(0)
read();
readName()
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
cv2.waitKey(10)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
frame,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.cv.CV_HAAR_SCALE_IMAGE
)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
f=gray[y:y+h,x:x+w]
f=cv2.resize(f,(92,112),interpolation=cv2.INTER_LANCZOS4)
cv2.imwrite("11.pgm",f)
label, confidence = model.predict(f)
print"Threshold : ", model.getDouble("threshold")
if label>-1:
if Labels[label] != textsay:
cmd = 'espeak "{0}" 2>/dev/null'.format(Labels[label])
os.system(cmd)
textsay=Labels[label]
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(frame,Labels[label],(x,y-10), font, 1.0,(255,255,255))
print "\n"+str(Labels[label])+" | "+str(confidence)
# Display the resulting frame
cv2.imshow('Video', frame)
k=cv2.waitKey(5)& 0xFF
if k==97 :
Add(faces,gray)
if k==27:
exit()
help me please i have this code:
import sys, pygame
pygame.init()
size = width, height = 800, 600
speed = [2, 2]
black = 1, 1, 1
screen = pygame.display.set_mode(size)
ball = pygame.image.load("ball.bmp")
ballrect = ball.get_rect()
player1 = pygame.image.load("player1.png")
player1rect = player1.get_rect()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
player1rect = player1rect.move(speed)
if player1rect.w < 0 or player1rect.s > heght:
speed[1] = -speed[1]
screen.fill(black)
screen.blit(ball, ballrect) (player1, player1rect)
pygame.display.flip()
and when i trying launch it it just saying:
Traceback (most recent call last):
File "C:\Users\User\Documents\Pong\pong.py", line 31, in <module>
screen.blit(ball, ballrect) (player1, player1rect)
TypeError: 'pygame.Rect' object is not callable
so is there anybody who can help me? and i have trying almost everything and it will not work and if there is something more wrong with my code so please write it.
(sorry for my bad english)
Replace line 31 with two lines that say:
screen.blit(ball, ballrect)
screen.blit(player1, player1rect)
This should fix your problem