Cannot import pygame.camera - import

I was trying this code to open a webcam with pygame
import pygame.camera
import pygame.image
import sys
pygame.camera.init()
cameras = pygame.camera.list_cameras()
print ("Using camera %s ..." % cameras[0])
webcam = pygame.camera.Camera(cameras[0])
webcam.start()
# grab first frame
img = webcam.get_image()
WIDTH = img.get_width()
HEIGHT = img.get_height()
screen = pygame.display.set_mode( ( WIDTH, HEIGHT ) )
pygame.display.set_caption("pyGame Camera View")
while True :
for e in pygame.event.get() :
if e.type == pygame.QUIT :
sys.exit()
# draw frame
screen.blit(img, (0,0))
pygame.display.flip()
# grab next frame
img = webcam.get_image()
but I got this import error:
...Python\Python39\lib\site-packages\pygame_camera_vidcapture.py", line 32, in init
from VideoCapture import vidcap as vc
ModuleNotFoundError: No module named 'VideoCapture'

Enter
pip install pygame.camera
into your terminal or command prompt depending on what you are using.

Related

How to rotate a bone to a specific position programmatically?

Suppose I have a human skeleton standing upright in the following position:
Say I want to modify the 3d model, so that it is raising one hand (everything else the same):
I couldn't find a picture of a skeleton standing upright, so I posted the above picture, but you can imagine if the skeleton was standing exactly how it was in the first picture, with the only difference being it had rotated its right should to raise its right hand perfectly upright, what would it look like?
To further illustrate the idea, if you visit this link:
Motion capture visualisation with Blender
The code he uses to update the 3d model in blender is actually quite small and simple:
import bge
import math
from math import *
import mathutils
import time
import sys
#sys.path.append("/usr/lib/python3/dist-packages")
import serial
import glob
port=''.join(glob.glob("/dev/ttyACM*"))
#port=''.join(glob.glob("/dev/ttyUSB*"))
#port=''.join(glob.glob("/dev/rfcomm"))
ser = serial.Serial(port,115200)
print("connected to: " + ser.portstr)
#Connect the suit first and after a ~second launch the script
# Get the whole bge scene
scene = bge.logic.getCurrentScene()
# Helper vars for convenience
source = scene.objects
# Get the whole Armature
main_arm = source.get('Armature')
ob = bge.logic.getCurrentController().owner
def updateAngles():
ser.write("a".encode('UTF-8'))
s=ser.readline()[:-3].decode('UTF-8') #delete ";\r\n"
angles=[x.split(',') for x in s.split(';')]
for i in range(len(angles)):
angles[i] = [float(x) for x in angles[i]]
trunk = mathutils.Quaternion((angles[4][0],angles[4][1],angles[4][2],angles[4][3]))
correction = mathutils.Quaternion((1.0, 0.0, 0.0), math.radians(90.0))
trunk_out = correction*trunk
upperLegR = mathutils.Quaternion((angles[5][0],angles[5][1],angles[5][2],angles[5][3]))
correction = mathutils.Quaternion((1.0, 0.0, 0.0), math.radians(90.0))
upperLegR_out = correction*upperLegR
lowerLegR = mathutils.Quaternion((angles[6][0],angles[6][1],angles[6][2],angles[6][3]))
correction = mathutils.Quaternion((1.0, 0.0, 0.0), math.radians(90.0))
#correction = mathutils.Quaternion((1.0, 0.0, 0.0), math.radians(90.0))
lowerLegR_out = correction*lowerLegR
upperLegL = mathutils.Quaternion((angles[7][0],angles[7][1],angles[7][2],angles[7][3]))
correction = mathutils.Quaternion((1.0, 0.0, 0.0), math.radians(90.0))
upperLegL_out = correction*upperLegL
lowerLegL = mathutils.Quaternion((angles[8][0],angles[8][1],angles[8][2],angles[8][3]))
correction = mathutils.Quaternion((1.0, 0.0, 0.0), math.radians(90.0))
lowerLegL_out = correction*lowerLegL
ob.channels['armR'].rotation_quaternion = mathutils.Vector([angles[0][0],angles[0][1],angles[0][2],angles[0][3]])
ob.channels['forearmR'].rotation_quaternion = mathutils.Vector([angles[1][0],angles[1][1],angles[1][2],angles[1][3]])
ob.channels['armL'].rotation_quaternion = mathutils.Vector([angles[2][0],angles[2][1],angles[2][2],angles[2][3]])
ob.channels['forearmL'].rotation_quaternion = mathutils.Vector([angles[3][0],angles[3][1],angles[3][2],angles[3][3]])
ob.channels['trunk'].rotation_quaternion = trunk_out
ob.channels['upperLegR'].rotation_quaternion = upperLegR_out
ob.channels['lowerLegR'].rotation_quaternion = lowerLegR_out
ob.channels['upperLegL'].rotation_quaternion = upperLegL_out
ob.channels['lowerLegL'].rotation_quaternion = lowerLegL_out
ob.update()
time.sleep(0.001)
Is there an equivalent way in Unity3d, to access a particular bone in a 3d model, and set its rotation ?
See this video:
https://www.youtube.com/watch?time_continue=26&v=JddtxynTgLk
As you can see, he is reading the values from the sensor, and updating the 3d model in blender in real time. I've done the sensor part, but am just getting started with Unity, and was wondering how to access individual bones and set them similar to the above code.
EDIT: In Godot engine, they seem to be able to do it very simply, see the link below:
https://docs.godotengine.org/en/3.0/tutorials/3d/working_with_3d_skeletons.html
extends Spatial
var skel
var id
func _ready():
skel = get_node("skel")
id = skel.find_bone("upperarm")
print("bone id:", id)
var parent = skel.get_bone_parent(id)
print("bone parent id:", id)
var t = skel.get_bone_pose(id)
print("bone transform: ", t)
set_process(true)
func _process(delta):
var t = skel.get_bone_pose(id)
t = t.rotated(Vector3(0.0, 1.0, 0.0), 0.1 * delta)
skel.set_bone_pose(id, t)
As you can see, in the Godot example also, once they get the bones id, they simply need to set the angle.

How to select a region with QRubberBand on a QLabel like in KSnapshot?

I am writing a screenshot utility with PyQt, and the idea is take a screenshot of the whole desktop, then display it in a QLabel, make the window full screen and user selects a region by mouse.
Is it possible to do this efficiently with a QLabel? I want the rubber band to stay on screen and it still can be tweaked. In this case, would I have to use QGraphicsScene?
Desired effect:
http://gfycat.com/SkinnyObeseAquaticleech
here is what I have so far
import sys
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import Qt, QPoint, QRect, QSize
from PyQt4.QtGui import QPixmap, QApplication, QLabel, QRubberBand
class MyLabel(QLabel):
def __init__(self, parent=None):
QLabel.__init__(self, parent)
self.rubberBand = QRubberBand(QRubberBand.Rectangle, self)
self.origin = QPoint()
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.origin = QPoint(event.pos())
self.rubberBand.setGeometry(QRect(self.origin, QSize()))
self.rubberBand.show()
def mouseMoveEvent(self, event):
if not self.origin.isNull():
self.rubberBand.setGeometry(
QRect(self.origin, event.pos()).normalized())
def mouseReleaseEvent(self, event):
if event.button() == Qt.LeftButton:
self.rubberBand.hide()
class mainUI(QtGui.QWidget):
def __init__(self):
super(mainUI, self).__init__()
self.initUI()
def initUI(self):
layout = QtGui.QVBoxLayout(self)
label = MyLabel(self)
pixmap = QPixmap.grabWindow(app.desktop().winId())
label.setPixmap(pixmap)
layout.addWidget(label)
self.setLayout(layout)
geometry = app.desktop().availableGeometry()
self.setFixedSize(geometry.width(), geometry.height())
# self.setWindowFlags( self.windowFlags() | Qt.FramelessWindowHint)
self.show()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = mainUI()
sys.exit(app.exec_())
Your approach is already quite far and I think it's possible to achieve what you want with a QLabel. I extended your example so that the rubber band stays on screen even after the mouse is released and you can drag the upper left and lower right corners of it.
You could extend it even more to drag the other corners and the sides and showing a label with the size in the middle.
In the picture you see the selection staying without the mouse pressed.
from PyQt4 import QtGui, QtCore
class RubberbandEnhancedLabel(QtGui.QLabel):
def __init__(self, parent=None):
QtGui.QLabel.__init__(self, parent)
self.selection = QtGui.QRubberBand(QtGui.QRubberBand.Rectangle, self)
def mousePressEvent(self, event):
'''
Mouse is pressed. If selection is visible either set dragging mode (if close to border) or hide selection.
If selection is not visible make it visible and start at this point.
'''
if event.button() == QtCore.Qt.LeftButton:
position = QtCore.QPoint(event.pos())
if self.selection.isVisible():
# visible selection
if (self.upper_left - position).manhattanLength() < 20:
# close to upper left corner, drag it
self.mode = "drag_upper_left"
elif (self.lower_right - position).manhattanLength() < 20:
# close to lower right corner, drag it
self.mode = "drag_lower_right"
else:
# clicked somewhere else, hide selection
self.selection.hide()
else:
# no visible selection, start new selection
self.upper_left = position
self.lower_right = position
self.mode = "drag_lower_right"
self.selection.show()
def mouseMoveEvent(self, event):
'''
Mouse moved. If selection is visible, drag it according to drag mode.
'''
if self.selection.isVisible():
# visible selection
if self.mode is "drag_lower_right":
self.lower_right = QtCore.QPoint(event.pos())
elif self.mode is "drag_upper_left":
self.upper_left = QtCore.QPoint(event.pos())
# update geometry
self.selection.setGeometry(QtCore.QRect(self.upper_left, self.lower_right).normalized())
app = QtGui.QApplication([])
screen_pixmap = QtGui.QPixmap.grabWindow(app.desktop().winId())
window = QtGui.QWidget()
layout = QtGui.QVBoxLayout(window)
label = RubberbandEnhancedLabel()
label.setPixmap(screen_pixmap)
layout.addWidget(label)
geometry = app.desktop().availableGeometry()
window.setFixedSize(geometry.width(), geometry.height())
window.show()
app.exec_()

AS3 Starling: How to remove black bars on top and bottom of iPhone 6+/...?

I'm just trying out Starling Framework for Actionscript 3 and I have a "big" problem with removing these ugly black bars on top and bottom of my iPhone 6+.
I tried to fix it with: http://wiki.starling-framework.org/manual/multi-resolution_development and http://forum.starling-framework.org/topic/game-not-full-screen-when-testing-in-ios
But it still wont work :(
Any Ideas?
package {
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.geom.Rectangle;
import starling.core.Starling;
import starling.events.ResizeEvent;
import starling.utils.HAlign;
import starling.utils.VAlign;
public class FooBar extends Sprite {
private
var _starling: Starling;
public
function CHouseApp() {
super();
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
Starling.handleLostContext = true;
var screenWidth: int = stage.fullScreenWidth;
var screenHeight: int = stage.fullScreenHeight;
var viewPort: Rectangle = new Rectangle(0, 0, screenWidth, screenHeight)
_starling = new Starling(MainApplication, stage, viewPort);
_starling.stage.stageWidth = 320;
_starling.stage.stageHeight = 480;
_starling.showStats = true;
_starling.showStatsAt(HAlign.LEFT, VAlign.BOTTOM);
_starling.start();
}
}
}
Screnshot:
(Black bars are marked with red arrow)
You need to include a launch image of name Default-568h#2x.png, of size 640x1136, Default-667h#2x of size 750x1334, Default-736h#3x of size 1242x2208 or iOS will launch the app with a resolution of 640x960, giving you the black bars. You can read the official documentation here
I got it!
I just had to add the following png's to the src folder! so simple :O
Default-375w-667h#2x.png
Default-414w-736h#3x.png
Default-568h#2x.png
Default.png
Default#2x.png
List item

Issue with Standalone in Processing

I have a sketch running in Processing 2.1.2, and it runs fine from the sketch window. When I try to export it to a standalone windows application, Processing creates the application.windows folder, which contains the 'lib' and 'source' subdirectories. But when I double-click the application, it just showing me a blank window.
Can anybody guide me on how do I resolve this issue?
Coding of program is given below:
import toxi.geom.*;
import toxi.geom.mesh.*;
import toxi.processing.*;
import processing.serial.*;
TriangleMesh mesh;
ToxiclibsSupport gfx;
PImage img;
String input;
Serial port;
int x,y,z;
void setup() {
size(448, 299,P3D);
println(Serial.list());
port = new Serial(this,Serial.list()[0], 9600);
port.bufferUntil('\n');
mesh=(TriangleMesh)new STLReader().loadBinary(sketchPath("check.stl"),STLReader.TRIANGLEMESH);
gfx=new ToxiclibsSupport(this);
img=loadImage("imagei.jpg");
}
void draw() {
background(img);
translate(width/2,height/2,0);
rotateX(radians(x)); // Pitch
rotateY(radians(y)); // Roll
rotateZ(radians(z)); // Yaw
directionalLight(192, 168, 128,0, -1000, -0.5);
directionalLight(255, 64, 0, 0.5f, -0.5f, -0.1f);
noStroke();
scale(2);
gfx.mesh(mesh,false);
}
void serialEvent(Serial port)
{
input = port.readString();
if(input != null) {
String[] values = split(input, " ");
println(values[0]);
println(values[1]);
println(values[2]);
x= int(values[0]);y= int(values[1]);z= int(values[2]);
}
}
Edit this line of program:
mesh=(TriangleMesh)new STLReader().loadBinary(sketchPath("check.stl"),STLReader.TRIANGLEMESH);
by:
mesh=(TriangleMesh)new STLReader().loadBinary(sketchPath("data/check.stl"),STLReader.TRIANGLEMESH);
and rest of the program is fine, just check it and let me know if you get any error.

unable to draw correctly in Gtk+3

I can draw in a single Gtk.DrawingArea, but when i try to do it for many, for example 50, i got some errors in drawing.
Here is the code you need to check out:
def aggiorna(self, args=()):
import random
import time
while True:
for i in self.indirizzi_ip:
self.r=random.randint(0,10)/10.0
self.g=random.randint(0,10)/10.0
self.b=random.randint(0,10)/10.0
self.cpu_info[i]['drawing_area'].show() #the drawing happens here
time.sleep(1)
def __draw(self, widget, context): #connected to Gtk.DrawingArea.show()
context.set_source_rgb(self.r, self.g, self.b) #random
context.rectangle(0, 0, widget.get_allocated_width(), widget.get_allocated_height())
context.fill()
1) why do i get errors in drawing?
2) why do Gtk.DrawingArea(s) change color ONLY when i update the window (for example i switch from a program to Gtk.DrawingArea window)?
3) why don't i get random colors for each Gtk.DrawingArea?
cant help you on this
because it only changes color when Gtk.DrawingArea repainted itself ("draw" signal)
the r,g,b should be inside "draw" function. you did construct r,g,b but since it's outside the draw function, it did not change while area repainted.
why the sleep?
** edited **
sample code:
....
win = Gtk.Window ()
box = Gtk.Box ()
self.square_list = []
for square in range (10):
self.darea = Gtk.DrawingArea ()
self.set_size_request (50,50)
self.square_list.append (self.darea)
box.add (self.darea)
#for each darea connect to separate "draw" signal
self.darea.connect ("draw", self,_draw)
aggiorna_button = Gtk.Button ('Aggiorna!!!') #sorry i use button
box.add (aggiorna_button)
aggiorna.button.connect ("clicked", self.aggiorna)
def _draw (self, widget, cr):
r = random.randint (0,10)/10.0
g = random.randint (0,10)/10.0
b = random.randint (0,10)/10.0
cr.set_source_rgb (r,g,b)
cr.rectangle (0,0, widget.get_allocated_width(), widget.get_allocated_height())
cr.fill ()
def aggiorna (self, widget):
for darea in self.square_list:
darea.queue_draw()