I'm a Newbie in OpenGl. I try to draw points with Pyglet. But if I change the configs of the window, to enable MSAA, the points disappear. For other primitives this is not the case. I think this is a OpenGL problem and not caused by Pyglet.
My goal is to use MSAA (for getting smooth lines) or config2 in example code and also see the points.
Please see the example code and switch between the different configs.
import pyglet
from pyglet.gl import *
config1 = Config(sample_buffers=1, samples=4)
config2 = Config(sample_buffers=1, samples=4, double_buffer=True)
window = pyglet.window.Window() # everything there, but no smooth line
# window = pyglet.window.Window(config = config1) # draws nothing
# window = pyglet.window.Window(config = config2) # draws only smooth line, points missing
batch = pyglet.graphics.Batch()
line = batch.add(2, pyglet.gl.GL_LINES, None, ('v2f', (270, 165, 370, 315)))
point = batch.add(2, pyglet.gl.GL_POINTS, None, ('v2f', (300, 165, 400, 315)))
#window.event
def on_draw():
window.clear()
batch.draw()
pyglet.app.run()
It's a problem with MSAA but I don't really understand why my Points disappear. Any fixes/explanations?
Related
How can I rotate a line in pygame using math module and every second rotate line delete old line. I've just used other code but the problem was old line rotate and so I watched an sunshine effect.
To easily assist you with a specific answer for your problem, you really need to show your code. Please see how to ask.
I've prepared a generic example that randomises one end point of a line when a mouse button is clicked.
# pyg_line_demo
import pygame
import random
def get_random_position():
"""return a random (x,y) position in the screen"""
return (random.randint(0, screen_width - 1), #randint includes both endpoints.
random.randint(0, screen_height - 1))
def random_line(line):
""" Randomise an end point of the line"""
if random.randint(0,1):
return [line[0], get_random_position()]
else:
return [get_random_position(), line[-1]]
# initialisation
pygame.init()
screen_width, screen_height = 640, 480
surface = pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption('Lines')
clock = pygame.time.Clock() #for limiting FPS
FPS = 30
# initial line
line = [(10, 10), (200, 200)]
finished = False
while not finished:
for event in pygame.event.get():
if event.type == pygame.QUIT:
finished = True
if event.type == pygame.MOUSEBUTTONDOWN:
line = random_line(line)
#redraw background
surface.fill(pygame.Color("white"))
#draw line
pygame.draw.aalines(surface, pygame.Color("blue"), False, line)
# update display
pygame.display.update()
#limit framerate
clock.tick(FPS)
pygame.quit()
You should be able to insert your line rotation function in place of the random_line() function.
Let us know if you have any further questions.
I am trying to make my raspberry pi detect face(s) in video feed from pi camera, this is my code
import time
import cv2
import sys
import numpy as np
from picamera.array import PiRGBArray
from picamera import PiCamera
# camera settings
camera = PiCamera()
camera.resolution = (640, 480)
camera.framerate = 32
rawCapture = PiRGBArray(camera, size=(640,480))
time.sleep(1)
# video input
faceCascade = cv2.CascadeClassifier('/home/pi/opencv-3.1.0/data/haarcascades/haarcascade_frontalface_default.xml')
# capture frame from the camera
for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
image = frame.array
# face detection
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.CASCADE_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)
#show the frames
cv2.imshow("Frame", image)
key = cv2.waitKey(1) & 0xFF
rawCapture.truncate(0)
if key == ord("q"):
break
I tried to run it, but i got this error message
Traceback (most recent call last):
File"/home/pi/pythonpy/videofacedet/craft/videofacedet(selfmade).py", line 21, in <module>
for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
File "/usr/lib/python2.7/dist-packages/picamera/camera.py", line 1702, in capture_continuous
if not encoder.wait(self.CAPTURE_TIMEOUT):
File "/usr/lib/python2.7/dist-packages/picamera/encoders.py", line 395, in wait
self.stop()
File "/usr/lib/python2.7/dist-packages/picamera/encoders.py", line 419, in stop
self._close_output()
File "/usr/lib/python2.7/dist-packages/picamera/encoders.py", line 349, in _close_output
mo.close_stream(output, opened)
File "/usr/lib/python2.7/dist-packages/picamera/mmalobj.py", line 371, in close_stream
stream.flush()
File "/usr/lib/python2.7/dist-packages/picamera/array.py", line 238, in flush
self.array = bytes_to_rgb(self.getvalue(), self.size or self.camera.resolution)
File "/usr/lib/python2.7/dist-packages/picamera/array.py", line 127, in bytes_to_rgb
'Incorrect buffer length for resolution %dx%d' % (width, height))
PiCameraValueError: Incorrect buffer length for resolution 640x480
where did it go wrong? I am new to python programming so I get confused about how can I fix it and where to start. Thank you in advance for your answers
Your code doesn't seem to be indented properly. I would suggest indenting these lines:
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
for (x, y, w, h) in faces:
to be indented the same as the line image = frame.array
I think that was the cause of the error since you're supposed to clear the current frame when you're done with it to prepare for the next frame and I see you're trying to do that with rawCapture.truncate(0).
Indentation is really important in python since that's how lines of code are treated as blocks. I see it as how curly braces in some programming languages treat lines of code as blocks.
I think maybe the framerate you set is too high, I delete the line camera.framerate= 32,then the camera window showed in screen.
I am reading in a GeoJSON file that contains two simple polygon descriptions that I made and six complicated vectors from http://ryanmullins.org/blog/2015/8/18/land-area-vectors-for-geographic-combatant-commands
I can read my own 4-8 point description into Shapely Polygons. However, the more complicated descriptions from the website above give me the following error:
from shapely.geometry import Polygon
jsonFile="path/to/file.json"
with open(jsonFile) as f:
data=json.load(f)
for feature in data['features']:
#This is not how I'm saving the polygons, and is only for testing purposes:
myPoly=Polygon(feature['geometry']['coordinates'])
The error message:
File "/.../anaconda2/lib/python2.7/site-packages/shapely/geometry/polygon.py", line 229, in __init__
self._geom, self._ndim = geos_polygon_from_py(shell, holes)
File "/.../anaconda2/lib/python2.7/site-packages/shapely/geometry/polygon.py", line 508, in geos_polygon_from_py
geos_shell, ndim = geos_linearring_from_py(shell)
File "/.../anaconda2/lib/python2.7/site-packages/shapely/geometry/polygon.py", line 454, in geos_linearring_from_py
assert (n == 2 or n == 3)
AssertionError
They are read as list, with USAFRICOM having length 113.
Is there a way to read these very long vectors into shapely? I have tried Polygon, MultiPoint, asMultiPointIf. If not, would you be able to suggest how to simplify this vector description into something that could be read by Shapely?
Well it gets a bit more complicated than just throwing all coordinates at Shapely in one go.
According to the GeoJSON spec and Shapely's documentation regarding multipolygons: MultiPolygons consist of arrays of Polygons, and Polygons again consist of LinearRings which depict outer and inner areas / holes.
Here's my attempt at a MultiPolygon reader for your GeoJSON files, opening the output back in QGIS shows up correctly, let me know if you have issues.
import json
from shapely.geometry import mapping
from shapely.geometry import Polygon
from shapely.geometry import LinearRing
from shapely.geometry import MultiPolygon
jsonFile = "USCENTCOM.json"
polygons = []
with open(jsonFile) as f:
data = json.load(f)
for feature in data['features']:
for multi_polygon in feature['geometry']['coordinates']:
# collect coordinates (LinearRing coordinates) for the Polygon
tmp_poly = []
for polygon in multi_polygon:
tmp_poly.append(polygon)
if len(tmp_poly) > 1:
# exterior LinearRing at [0], all following interior/"holes"
polygons.append(Polygon(tmp_poly[0], tmp_poly[1:]))
else:
# there's just the exterior LinearRing
polygons.append(Polygon(tmp_poly[0]))
# finally generate the MultiPolygon from our Polygons
mp = MultiPolygon(polygons)
# print GeoJSON string
print(json.dumps(mapping(mp)))
I am stuck when I try to place an image on my GUI. Based on the program I am working on, I am restricted to working with Python v2.7.11. I have a basic GUI that I pulled from elsewhere (shown below, top code). However, when I try to place an image using a similar process, my GUI goes away altogether (no other features show). Edit: The error I am receiving is "image "pyimage28" doesn't exist, even though I'm defining my image as 'bug.gif'. The full error message is shown in the second code snippet; both the code and the image are located in on the Desktop.
Based on another question on this site, my attempt is shown below, starting with the variable "label".
Ultimately, I would like to do two things.
Place an image in the upper left corner of the GUI in place of where the frame item was
Give that image properties, such that I can store x,y coordinates when I click somewhere on the image, or the coordinates show in real time outside of the image.
.
from Tkinter import *
import ttk
root = Tk()
content = ttk.Frame(root)
#frame = ttk.Frame(content, borderwidth=5, relief="sunken", width=200, height=100)
label = ttk.Label(root)
image1 = PhotoImage(file='bug.gif')
label['image'] = image1
latlbl = ttk.Label(content, text="Latitude")
latval = ttk.Entry(content)
lonlbl = ttk.Label(content, text="Longitude")
lonval = ttk.Entry(content)
onevar = BooleanVar()
twovar = BooleanVar()
threevar = BooleanVar()
onevar.set(True)
twovar.set(False)
threevar.set(True)
one = ttk.Checkbutton(content, text="One", variable=onevar, onvalue=True)
two = ttk.Checkbutton(content, text="Two", variable=twovar, onvalue=True)
three = ttk.Checkbutton(content, text="Three", variable=threevar, onvalue=True)
ok = ttk.Button(content, text="Okay")
cancel = ttk.Button(content, text="Cancel")
content.grid(column=0, row=0)
#frame.grid(column=0, row=0, columnspan=3, rowspan=2)
label.grid(column=0, row=0, columnspan=3, rowspan=2)
latlbl.grid(column=3, row=0, columnspan=1)
latval.grid(column=4, row=0, columnspan=2)
lonlbl.grid(column=3, row=1, columnspan=1)
lonval.grid(column=4, row=1, columnspan=2)
one.grid(column=0, row=3)
two.grid(column=1, row=3)
three.grid(column=2, row=3)
ok.grid(column=3, row=3)
cancel.grid(column=4, row=3)
label.pack()
root.mainloop()
The full code error is:
runfile('C:/Users/ajpung/Desktop/untitled9.py', wdir='C:/Users/ajpung/Desktop')
Traceback (most recent call last):
File "<ipython-input-1-1596c9c787bc>", line 1, in <module>
runfile('C:/Users/ajpung/Desktop/untitled9.py', wdir='C:/Users/ajpung/Desktop')
File "C:\Users\ajpung\AppData\Local\Continuum\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 699, in runfile
execfile(filename, namespace)
File "C:\Users\ajpung\AppData\Local\Continuum\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 74, in execfile
exec(compile(scripttext, filename, 'exec'), glob, loc)
File "C:/Users/ajpung/Desktop/untitled9.py", line 25, in <module>
label['image'] = image1
File "C:\Users\ajpung\AppData\Local\Continuum\Anaconda2\lib\lib-tk\Tkinter.py", line 1333, in __setitem__
self.configure({key: value})
File "C:\Users\ajpung\AppData\Local\Continuum\Anaconda2\lib\lib-tk\Tkinter.py", line 1326, in configure
return self._configure('configure', cnf, kw)
File "C:\Users\ajpung\AppData\Local\Continuum\Anaconda2\lib\lib-tk\Tkinter.py", line 1317, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
TclError: image "pyimage1" doesn't exist
The code you posted does not give the error you say it does when running in a standard python interpreter.
That being said, there is one critical bug in your code that will prevent it from working. You are using both grid and pack in the root window. You need to remove this line:
label.pack()
I thought I'd tried this before, but the problem isn't with Spyder. Switching root = Tk() to root = Toplevel() fixed the original issue.
I have moved on to messing with Pygame recently, and I started following tutorials. Everything has ran fine up until I reached a program that looks like so:
"""
A python graphics introduction.
This simple program draws lines at a 45 degree angle from one side
of the screen to the other.
"""
# Import a library of functions called 'pygame'
import pygame
from pygame import font
# Initialize the game engine
pygame.init()
# Set the height and width of the screen
size = (400, 500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Intro to Graphics")
#Loop until the user clicks the close button.
done = False
clock = pygame.time.Clock()
# Loop as long as done == False
while not done:
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done = True # Flag that we are done so we exit this loop
# All drawing code happens after the for loop and but
# inside the main while not done loop.
# Clear the screen and set the screen background
screen.fill(WHITE)
# Select the font to use, size, bold, italics
font = pygame.font.SysFont('Calibri', 25, True, False)
# Render the text. "True" means anti-aliased text.
# Black is the color. This creates an image of the
# letters, but does not put it on the screen
text = font.render("My text", True, BLACK)
# Put the image of the text on the screen at 250x250
screen.blit(text, [250, 250])
# Go ahead and update the screen with what we've drawn.
# This MUST happen after all the other drawing commands.
pygame.display.flip()
# This limits the while loop to a max of 60 times per second.
# Leave this out and we will use all CPU we can.
clock.tick(60)
# Be IDLE friendly
pygame.quit()
When ran I get an error at font = pygame.font.SysFont('Calibri', 25, True, False) that looks like:
RuntimeWarning: use font: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/font.so, 2): Library not loaded: /usr/X11/lib/libfreetype.6.dylib
Referenced from: /Library/Frameworks/SDL_ttf.framework/Versions/A/SDL_ttf
Reason: image not found
(ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/font.so, 2): Library not loaded: /usr/X11/lib/libfreetype.6.dylib
Referenced from: /Library/Frameworks/SDL_ttf.framework/Versions/A/SDL_ttf
Reason: image not found)
pygame.font.init()
Traceback (most recent call last):
File "IntroGraphics.py", line 15, in <module>
pygame.font.init()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/__init__.py", line 70, in __getattr__
raise NotImplementedError(MissingPygameModule)
NotImplementedError: font module not available
(ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/font.so, 2): Library not loaded: /usr/X11/lib/libfreetype.6.dylib
Referenced from: /Library/Frameworks/SDL_ttf.framework/Versions/A/SDL_ttf
Reason: image not found)
I have looked on here for an answer, and the only other post about it involves 32-bit Pygame with 64-bit Python. I have made sure both of them are running 32-bit (Despite the fact it's a 64-bit machine. Pygame is only 32-bit.). I am running Python 2.7.9 Fresh Install
Other places say it's a problem with SDL, but I am inexperienced with SDL and I wouldn't know what to do.
Has anyone else had this problem?
The fonts that are available to pygame might be different on different computers. I suggest seeing if the font you want to use is included on your computer. You can see the all the available fonts with this command:
pygame.font.get_fonts()
# returns a list of available fonts
You can also get the system's default fort by using this command:
pygame.font.get_default_font()
# returnes the name of the default font
You can use this code to check your font:
if 'Calibri' in pygame.font.get_fonts():
font_name = 'Calibri'
else:
font_name = pygame.font.get_default_font()