Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-6 of 6 total  RSS 

Simple camera class in FTS - lookAt function.

// Camera class for FTS

/// Makes the camera look at a certain point.
/** This function makes the camera look at a certain point. If that point is the same as its
 *  current position, the camera moves back the (current) distance |camera-target|.
 *
 * \param in_vTgt The position where the camera should look at.
 *
 * \return If successfull: ERR_OK
 * \return If failed:      An error code < 0
 *
 * \author Pompei2
 */
CFTSCamera *CFTSCamera::lookAt(const CFTSVector & in_vTgt)
{
    // Calculate the new front vector that points to the target.
    CFTSVector vNewFront = (in_vTgt - m_vPos).normalize();

    // The two vectors are in one plane. This gives us the cosine of the angle between
    // these two vectors.
    float fDotProd = vNewFront.dot(m_vFront);
    if(fDotProd > 1.0f || fDotProd < -1.0f)
        return this;

    // By getting the arc cosine of this, we get the angle in radians between the two
    // vectors. But we only get an angle between 0 and pi, that will be a problem.
    float fAlpha = acosf(fDotProd);

    // Here we get the normal to these two vectors, we will need to rotate our front
    // vector around this normal.
    CFTSVector vNormal = vNewFront.cross(m_vFront).normalize();

    // As I said, we have a problem: as we only get an angle between 0 and pi,
    // we don't know if we need to rotate clockwise or counterclockwise ...
    // We solve this problem by just trying it out.
    CFTSVector vFrontTest = m_vFront.rotate(vNormal, fAlpha);

    // If the dot product is near to one, it means we were right. with our guess
    // rotating counterclockwise.
    // Else, we must rotate clockwise.
    fDotProd = vFrontTest.dot(vNewFront);
    if(fabs(fDotProd) > (1.0f - D_FTS_DELTA)) {
            m_vFront = vFrontTest;
            m_vUp = m_vUp.rotate(vNormal, fAlpha);
            m_vRight = m_vRight.rotate(vNormal, fAlpha);
    } else {
            m_vFront = m_vFront.rotate(vNormal, -fAlpha);
            m_vUp = m_vUp.rotate(vNormal, -fAlpha);
            m_vRight = m_vRight.rotate(vNormal, -fAlpha);
    }

    // If the dot product is near to -1, it means we look the wrong way.
    // To correct this, we just rotate pi radians (a half circle).
    if(fDotProd < -(1.0f - D_FTS_DELTA))
        this->rotateYRadians(M_PI);

    return this;
}

Simple camera class in FTS

// Simple camera class in FTS

/**
 * \file camera.cpp
 * \author Pompei2
 * \date 15 July 2006
 * \brief This file contains the camera class implementation.
 **/

#include "3d/camera.h"

#include <GL/gl.h>

#ifdef DEBUG
#  define new new(__FILE__,__LINE__)
#endif

/// Constructor
CFTSCamera::CFTSCamera( void )
{
    m_vRight = CFTSVector(1.0f,0.0f,0.0f);
    m_vUp    = CFTSVector(0.0f,1.0f,0.0f);
    m_vFront = CFTSVector(0.0f,0.0f,-1.0f);
}

/// Destructor
CFTSCamera::~CFTSCamera( void )
{
}

/// Places the camera at a certain point.
/** This function places the camera at a certain point in space.
 *
 * \param in_vPos The new position of the camera.
 *
 * \return If successfull: ERR_OK
 * \return If failed:      An error code < 0
 *
 * \author Pompei2
 */
CFTSCamera *CFTSCamera::pos(const CFTSVector & in_vPos)
{
    m_vPos = in_vPos;
    return this;
}

/// Moves the camera to the right.
/** This moves the camera to the right. The right is relative to the
 *  camera's orientation ! To move to the left, put a negative value here.
 *
 * \param in_fAmount The amount of units to move to the right.
 *
 * \author Pompei2
 */
CFTSCamera *CFTSCamera::moveRight(float in_fAmount)
{
    // We have a vector pointing to the right,
    // so moving to the right is an easy thing:
    // Just add a multiple of this vector to the current position.
    m_vPos = m_vPos + m_vRight.scalar(in_fAmount);

    return this;
}

/// Moves the camera to the front.
/** This moves the camera to the front. The right is relative to the
 *  camera's orientation and to be exact, it is where the camera looks at.
 *  Moving to the front is a bit like zooming in.
 *  To move back (like zoom out), put a negative value here.
 *
 * \param in_fAmount The amount of units to move to the front.
 *
 * \author Pompei2
 */
CFTSCamera *CFTSCamera::moveFront(float in_fAmount)
{
    // Same as for moveRight.
    m_vPos = m_vPos + m_vFront.scalar(in_fAmount);

    return this;
}

/// Moves the camera upwards.
/** This moves the camera upwards. Upwards is the direction that is perpendicular
 *  To your right and to your front, and shows up :) It is like the top of your head.
 *  To move downwards (to your feets), put a negative value here.
 *
 * \param in_fAmount The amount of units to move up.
 *
 * \author Pompei2
 */
CFTSCamera *CFTSCamera::moveUp(float in_fAmount)
{
    // Same as for moveRight.
    m_vPos = m_vPos + m_vUp.scalar(in_fAmount);

    return this;
}

/// Rotates the camera around ITS x axis.
/** This rotates the camera around THE CAMERA's x axis.
 *  This basically means it looks up or down. As seen from the right,
 *  a positive value rotates counterclockwise (look up) and a negative
 *  value rotates clockwise (look down).
 *
 * \param in_fAmount The amount of degrees to rotate.
 *
 * \author Pompei2
 */
CFTSCamera *CFTSCamera::rotateX(float in_fAmount)
{
    Lib3dsMatrix mRotation;
    Lib3dsQuat qRotation;

    // First, clean the matrix.
    lib3ds_matrix_identity(mRotation);

    // Create the quaternion to rotate, we need the angle in radians.
    lib3ds_quat_axis_angle(qRotation, m_vRight.lib3ds(), -RADIANS(in_fAmount));

    // Apply the rotation to the identity matrix, creating a transformation matrix.
    lib3ds_matrix_rotate(mRotation, qRotation);

    // Rotate our front and up vectors, this makes the camera rotate.
    m_vFront = m_vFront.transform(mRotation).normalize();
    m_vUp = m_vUp.transform(mRotation).normalize();

    return this;
}

/// Rotates the camera around ITS y axis.
/** This rotates the camera around THE CAMERA's y axis.
 *  This basically means it looks left or right. As seen from the top,
 *  a positive value rotates counterclockwise (look left) and a negative
 *  value rotates clockwise (look right).
 *
 * \param in_fAmount The amount of degrees to rotate.
 *
 * \author Pompei2
 */
CFTSCamera *CFTSCamera::rotateY(float in_fAmount)
{
    Lib3dsMatrix mRotation;
    Lib3dsQuat qRotation;

    // First, clean the matrix.
    lib3ds_matrix_identity(mRotation);

    // Create the quaternion to rotate, we need the angle in radians.
    lib3ds_quat_axis_angle(qRotation, m_vUp.lib3ds(), -RADIANS(in_fAmount));

    // Apply the rotation to the identity matrix, creating a transformation matrix.
    lib3ds_matrix_rotate(mRotation, qRotation);

    // Rotate our front and up vectors, this makes the camera rotate.
    m_vFront = m_vFront.transform(mRotation).normalize();
    m_vRight = m_vRight.transform(mRotation).normalize();

    return this;
}

/// Rotates the camera around ITS z axis.
/** This rotates the camera around THE CAMERA's z axis.
 *  This is the same effect as if you rotate your head to bring an ear
 *  close to the shoulder. A positive value rotates counterclockwise (left shoulder)
 *  and a negative value rotates clockwise (right shoulder).
 *
 * \param in_fAmount The amount of degrees to rotate.
 *
 * \author Pompei2
 */
CFTSCamera *CFTSCamera::rotateZ(float in_fAmount)
{
    Lib3dsMatrix mRotation;
    Lib3dsQuat qRotation;

    // First, clean the matrix.
    lib3ds_matrix_identity(mRotation);

    // Create the quaternion to rotate, we need the angle in radians.
    lib3ds_quat_axis_angle(qRotation, m_vFront.lib3ds(), -RADIANS(in_fAmount));

    // Apply the rotation to the identity matrix, creating a transformation matrix.
    lib3ds_matrix_rotate(mRotation, qRotation);

    // Rotate our front and up vectors, this makes the camera rotate.
    m_vUp = m_vUp.transform(mRotation).normalize();
    m_vRight = m_vRight.transform(mRotation).normalize();

    return this;
}

/// Renders the camera.
/** This function applies all transformations to the current matrix
 *  that are needed to place the camera.
 *
 * \author Pompei2
 */
CFTSCamera *CFTSCamera::render(void)
{
    // gluLookAt wants a point in space to look at, not just a direction.
    // Calculate this point.
    CFTSVector vLookAt = m_vPos + m_vFront;

    // Let gluLookAt do all the matrix calculation stuff.
    gluLookAt(m_vPos.x(), m_vPos.y(), m_vPos.z(),
              vLookAt.x(), vLookAt.y(), vLookAt.z(),
              m_vUp.x(), m_vUp.y(), m_vUp.z());

    return this;
}

Like a Touch screen in the air... Like a mouse with a pencil.

I had create a motion detection that find a black pixel in the square, and centralize on it.
Its very simple but very fun!

References
http://www.danilocesar.com/blog/2006/12/03/smartphones-aonde-podemos-parar

If you want to see this working:
http://www.youtube.com/watch?v=sjm_g9MSYPc



#################################################################
# Developed by Danilo Cesar [http://www.danilocesar.com]
# Inspired on:  http://www.bigbold.com/snippets/posts/show/636
#################################################################

from appuifw import *
from graphics import Image
import camera, e32

app.body = c = Canvas()

running = 1
def quit():
    global running
    running = 0

app.exit_key_handler=quit
app.title = u"O controle"
app.screen = 'full'   # or 'normal', 'large'

def getdata(im, bpp=24):
    import struct, zlib
    im.save('D:\\pixels.png', bpp=bpp, compression='no')
    f = open('D:\\pixels.png', 'rb')
    f.seek(8 +8+13+4)
    chunk = []
    while 1:
        n = struct.unpack('>L', f.read(4))[0]
        if n==0: break  # 'IEND' chunk
        f.read(4) # 'IDAT'
        chunk.append(f.read(n))
        f.read(4)   # CRC
    f.close()
    return zlib.decompress(''.join(chunk))  # '\x00' prefix each line


X = 80
Y = 60
while running:
    if X < 0: X = 0
    if Y< 0: Y = 0
    if X > 160 - 30: X = 160 - 30
    if Y > 120 - 30: Y = 120-30
    im = camera.take_photo('RGB', (160,120))
    im.rectangle([(X,Y),(X+30,Y+30)], 0xff0000)   # red outline
    # check hot spot whether active
    box = Image.new((30,30), 'L')  # gray scale
    box.blit(im, (X,Y,X+30,Y+30))
    data = getdata(box, 8)

    # check black
    for i in range(len(data)):
        if ord(data[i]) < 30 and ord(data[i]) > 0:
            X += i%31 - 15
            Y += int(i/31) - 15
            break

    c.blit(im, (0,0), (8,12))   # show camera
 


Motion detection as input

Inspired from the PIL version here
http://gumuz.looze.net/wordpress/index.php/archives/2005/06/06/python-webcam-fun-motion-detection/

First with typical import and Canvas, exit setup
from appuifw import *
from graphics import Image
import camera, e32
#import miso    # don't dim the light

app.body = c = Canvas()

running = 1
def quit():
    global running
    running = 0
app.exit_key_handler=quit

Then the getdata function that reads pixel data
from image by saving/reading PNG.
def getdata(im, bpp=24):
    import struct, zlib
    im.save('D:\\pixels.png', bpp=bpp, compression='no')
    f = open('D:\\pixels.png', 'rb')
    f.seek(8 +8+13+4)
    chunk = []
    while 1:
        n = struct.unpack('>L', f.read(4))[0]
        if n==0: break  # 'IEND' chunk
        f.read(4) # 'IDAT'
        chunk.append(f.read(n))
        f.read(4)   # CRC
    f.close()
    return zlib.decompress(''.join(chunk))  # '\x00' prefix each line

Lastly, the real code follows.
last1 = '\x00' * 930    # can be anything
while running:
    im = camera.take_photo('RGB', (160,120))
    im.rectangle([(10,10),(40,40)], 0xff0000)   # red outline
    im.rectangle([(120,10),(150,40)], 0xff0000) # no code for this square
    # check hot spot whether active
    box = Image.new((30,30), 'L')  # gray scale
    box.blit(im, (10,10,40,40))
    data = getdata(box, 8)
    # check difference for motion
    pixdiff = 0
    for i in range(len(data)):
        if abs(ord(data[i])-ord(last1[i])) > 15:  # pix threshold 15/256
            pixdiff += 1
            if pixdiff > 90:    # img threshold 90/900
                im.rectangle([(10,10),(40,40)], fill=0xff0000)  # fill
                break           # motion detected
    last1 = data
    c.blit(im, (0,0), (8,12))   # show camera
    #miso.reset_inactivity_time()

When measured, it takes around 1.1 sec for each loop.
Compared this with 0.9 sec without image processing,
out code is quite efficient.

Camera preview

Taken (will some mod.) from
http://discussion.forum.nokia.com/forum/showthread.php?s=&threadid=63464

pys60 (the full name is python for series 60) 1.1.3
provide both camera and graphics display.
So, it is trivial to take photo and preview.
from appuifw import *
import camera

canvas=Canvas()
app.body=canvas

running=1
def quit():
    global running
    running=0
app.exit_key_handler=quit

while running:
    image = camera.take_photo(size= (160,120))
    canvas.blit(image, target=(8, 12, 168, 132))  # center it

Here I use the small size (160x120) for preview.
When the real photo is taken I can use the full (defualt)
size of (640x480) on my 6600 phone.

New camera module

A few days ago, I posted an example of how to take
a photo with py_s60 1.1.0. But now, a new and better
version (1.1.3) is released. The camera module has
improved significantly.

Now it can
- use different sizes (640x480 and 160x120 in my case)
- use zoom (0 or 1 in my case)
- take photos at 12, 16 or 24-bit color ('RGB12', 'RGB16', 'RGB')
- using flash ('none', 'auto', 'forced', 'fill_in', 'red_eye_reduce')
- set white-balance and exposure (I use 'auto' for both,
but sometimes I may use 'night' exposure)
- return an image object which can save in 'jpg' or 'png' format

You can see that these have good default values
 # copy from camera.py
def take_photo(
  mode='RGB16',
  size=(640, 480),
  zoom=0,
  flash='none',
  exposure='auto',
  white_balance='auto'):

So the simplest example is
import camera
im = camera.take_photo()  # use all default values
im.save(u'C:\\test.jpg')

You can see what you can set on your phone
from camera import *
print image_modes()
print image_sizes()
print max_zoom()
print flash_modes()
print exposure_modes()
print white_balance_modes()

« Newer Snippets
Older Snippets »
Showing 1-6 of 6 total  RSS