Skip to content

Tag: C

Cedilha no Ubuntu 16.04

    çççç
  ççç  ççç 
  ççç  ççç 
  ççç 
  ççç 
  ççç  ççç 
    çççç
     çç
    çç

Fiz esse script (cedilha.sh) pra fazer o c-cedilha (ç) funcionar no Ubuntu 16.04. Como é uma tarefa chata que eu já tive que fazer muitas vezes fica mais fácil pra mim ter um script pra fazer isso e pode ser que seja útil a outras pessoas. Infelizmente é uma solução que exige baixar e executar como root um script da internet. Eu recomendo que você leia o script e entenda o que está acontecendo antes de executá-lo. Esse script altera vários arquivos importantes e ele faz um backup (.bak) desses arquivos.

[bash]wget https://raw.githubusercontent.com/silveira/cedilha.sh/master/cedilha.sh
sudo bash cedilha.sh[/bash]

Por favor, se o script funcionou pra você também, diga nos comentários. Se você não está usando Ubuntu 16.04 e quer testar o script ainda assim, edite o script e remova a verificação no inicio do programa.

C# class properties example

A example of use of C# class properties to convert temperatures in Celsius, Fahrenheit or Kelvin. The temperature is encapsulated and stored in a internal representation, in this example, in Celcius (private double c). Each conversion is accessible by getting or setting a property.

using System;

public class Temperature {
	private double c;

	public double celsius {
		get {
			return c;
		}
		set {
			c = value;
		}
	}

	public double fahrenheit {
		get {
			return (c * 9 / 5) + 32;
		}
		set {
			c = (value - 32) * 5 / 9;
		}
	}

	public double kelvin {
		get {
			return c + 273.15;
		}
		set {
			c = value - 273.15;
		}
	}
}

public class TemperatureExample {
	public static void Main(string[] args) {
		Temperature fortaleza = new Temperature();
		fortaleza.celsius = 26;

		Temperature washington = new Temperature();
		washington.fahrenheit = 32;

		Temperature sun = new Temperature();
		sun.kelvin = 5778;

		Console.WriteLine("Fortaleza {0}°C / {1}°F / {2} K",
			fortaleza.celsius, fortaleza.fahrenheit, fortaleza.kelvin);
		Console.WriteLine("Washington {0}°C / {1}°F / {2} K",
			washington.celsius, washington.fahrenheit, washington.kelvin);
		Console.WriteLine("Sun {0}°C / {1}°F / {2} K",
			sun.celsius, sun.fahrenheit, sun.kelvin);
	}
}

Output:

Fortaleza 26°C / 78.8°F / 299.15 K
Washington 0°C / 32°F / 273.15 K
Sun 5504.85°C / 9940.73°F / 5778 K

There is some good examples of C# class properties at Using Properties (C# Programming Guide) at MSDN.

Atiaia early releases

This was a project that me and Marco Diego created during our graduation for the Computer Graphics course. It is a ray tracing engine build from scratch in C. It was great exercise of experimentation on how implement object-oriented design patterns in ANSI C. Later Marco continued it in his master’s degree thesis implementing more features.

Parts of the sources were lost during a disk failure in the forge we hosted the project. I found some early releases and packed them here for future use. It can be useful for someone studying C or how to implement a ray tracer.

Download: atiaia_sources_by_2006.zip

Enjoy it.

ps: with this project we won the 1st place project of class and maximum grade. ;)

Tiled TMX Map Loader for Pygame

I’m using the Tiled Map Editor for a while, I even wrote that tutorial about it. It’s a general purpose tile map editor, written in Java but now migrating to C++ with Qt, that can be easily used with my set of free pixelart tiles.

map editor tiles tileset game deveopment

A map done with Tiled is stored in a file with TMX extension. It’s just a XML file, easy to understand.

As I’m creating a map loader for my owns purposes, the procedure I’m doing here works we need some simplifications. I’m handling orthogonal maps only. I’m not supporting tile properties as well. I also don’t want to handle base64 and zlib encoding in this version, so in the Tiled editor, go at the menu Edit → Preferences and in the Saving tab unmark the options “Use binary encoding” and “Compress Layer Data (gzip)”, like this:

Tiled Preferences Window

When saving a map it will produce a TMX file like this:




 
  
  
 
 
  
 
 
  
   
   
    ...
   
   
  
 

For processing it on Python I’m using the event oriented SAX approach for XML. So I create a ContentHandler that handles events the start and end of XML elements. In the first element, map, I know enough to create a Pygame surface with the correct size. I’m also storing the map properties so I can use it later for add some logics or effects on the map. After that we create a instance of the Tileset class from where we will get the each tile by an gid number. Each layer has it’s a bunch of gids in the correct order. So it’s enough information to mount and draw a map.

# Author: Silveira Neto
# License: GPLv3
import sys, pygame
from pygame.locals import *
from pygame import Rect
from xml import sax

class Tileset:
    def __init__(self, file, tile_width, tile_height):
        image = pygame.image.load(file).convert_alpha()
        if not image:
            print "Error creating new Tileset: file %s not found" % file
        self.tile_width = tile_width
        self.tile_height = tile_height
        self.tiles = []
        for line in xrange(image.get_height()/self.tile_height):
            for column in xrange(image.get_width()/self.tile_width):
                pos = Rect(
                        column*self.tile_width,
                        line*self.tile_height,
                        self.tile_width,
                        self.tile_height )
                self.tiles.append(image.subsurface(pos))

    def get_tile(self, gid):
        return self.tiles[gid]

class TMXHandler(sax.ContentHandler):
    def __init__(self):
        self.width = 0
        self.height = 0
        self.tile_width = 0
        self.tile_height = 0
        self.columns = 0
        self.lines  = 0
        self.properties = {}
        self.image = None
        self.tileset = None

    def startElement(self, name, attrs):
        # get most general map informations and create a surface
        if name == 'map':
            self.columns = int(attrs.get('width', None))
            self.lines  = int(attrs.get('height', None))
            self.tile_width = int(attrs.get('tilewidth', None))
            self.tile_height = int(attrs.get('tileheight', None))
            self.width = self.columns * self.tile_width
            self.height = self.lines * self.tile_height
            self.image = pygame.Surface([self.width, self.height]).convert()
        # create a tileset
        elif name=="image":
            source = attrs.get('source', None)
            self.tileset = Tileset(source, self.tile_width, self.tile_height)
        # store additional properties.
        elif name == 'property':
            self.properties[attrs.get('name', None)] = attrs.get('value', None)
        # starting counting
        elif name == 'layer':
            self.line = 0
            self.column = 0
        # get information of each tile and put on the surface using the tileset
        elif name == 'tile':
            gid = int(attrs.get('gid', None)) - 1
            if gid <0: gid = 0
            tile = self.tileset.get_tile(gid)
            pos = (self.column*self.tile_width, self.line*self.tile_height)
            self.image.blit(tile, pos)

            self.column += 1
            if(self.column>=self.columns):
                self.column = 0
                self.line += 1

    # just for debugging
    def endDocument(self):
        print self.width, self.height, self.tile_width, self.tile_height
        print self.properties
        print self.image

def main():
    if(len(sys.argv)!=2):
        print 'Usage:\n\t{0} filename'.format(sys.argv[0])
        sys.exit(2)
    pygame.init()
    screen = pygame.display.set_mode((800, 480))
    parser = sax.make_parser()
    tmxhandler = TMXHandler()
    parser.setContentHandler(tmxhandler)
    parser.parse(sys.argv[1])
    while 1:
        for event in pygame.event.get():
            if event.type == QUIT:
                return
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                return
        screen.fill((255,255,255))
        screen.blit(tmxhandler.image, (0,0))
        pygame.display.flip()
        pygame.time.delay(1000/60)

if __name__ == "__main__": main()

Here is the result for opening a four layers map file:

netbeans python openning map

That’s it. You can get this code and adapt for your game because next versions will be a lot more coupled for my own purposes and not so general.

Download:packagemaploader.tar.bz2 It’s the Netbeans 6.7 (Python EA 2) project file but that can be opened or used with another IDE or without one. Also contains the village.tmx map and the tileset.

OpenCV: adding two images

This is a very simple example of how to open two images and display them added.

I got two pictures at project Commons from Wikimedia that were highlighted on Featured Pictures. I did a crop on both to have the same size, as I’m trying to make this example as simple as possible.

The first one is a photo of our Milky Way, taken at Paranal Observatory by Stéphane Guisard.

milkyway

The second one is a California surfer inside wave, taken by Mila Zinkova.

surfer

In this simple OpenCV code below, we open the images, create a new one to display the result and use cvAdd to add them. We do not save the result or handle more than the ordinary case of two images with the same size.

#include 
#include 
#include 

int main( int argc, char **argv ){
    IplImage *surfer, *milkyway, *result;
    int key = 0;
    CvSize size;

    /* load images, check, get size (both should have the same) */
    surfer = cvLoadImage("surfer.jpg", CV_LOAD_IMAGE_COLOR);
    milkyway = cvLoadImage("milkyway.jpg", CV_LOAD_IMAGE_COLOR);
    if((!surfer)||(!milkyway)){
        printf("Could not open one or more images.");
        exit -1;
    }
    size = cvGetSize(surfer);

    /* create a empty image, same size, depth and channels of others */
    result = cvCreateImage(size, surfer->depth, surfer->nChannels);
    cvZero(result);

    /* result = surfer + milkyway (NULL mask)*/
    cvAdd(surfer, milkyway, result, NULL);
 
    /* create a window, display the result, wait for a key */
    cvNamedWindow("example", CV_WINDOW_AUTOSIZE);
    cvShowImage("example", result);
    cvWaitKey(0);

    /* free memory and get out */
    cvDestroyWindow("example");
    cvReleaseImage(&surfer);
    cvReleaseImage(&milkyway);
    cvReleaseImage(&result);
    return 0;
}

/* gcc add.c -o add `pkg-config opencv --libs --cflags` */

Compile it (on a well configured OpenCV development environment) and run it:

gcc add.c -o add `pkg-config opencv –libs –cflags`
./add

The result got pretty cool, a milky way surfer.

surfer in the milk way

Simple Face Detection Player

Here’s a simple video player that also performs facial detection thought the Open Computer Vision Library.

Here’s a code developed using codes from nashruddin.com and samples from OpenCV, including the haar classifier xml. More detailed explanation on the theory about how the OpenCV face detection algorithm works can be found here.

The code:

#include 
#include 
#include 

CvHaarClassifierCascade *cascade;
CvMemStorage *storage;

int main(int argc, char *argv[]) {
    CvCapture *video = NULL;
    IplImage *frame = NULL;
    int delay = 0, key, i=0;
    char *window_name = "Video";
    char *cascadefile = "haarcascade_frontalface_alt.xml";

    /* check for video file passed by command line */
    if (argc>1) {
        video = cvCaptureFromFile(argv[1]);
    }
    else {
        printf("Usage: %s VIDEO_FILE\n", argv[0]);
        return 1;
    }

    /* check file was correctly opened */
    if (!video) {
        printf("Unable to open \"%s\"\n", argv[1]);
        return 1;
    }

    /* load the classifier */
    cascade = ( CvHaarClassifierCascade* )cvLoad( cascadefile, 0, 0, 0 );
    if(!cascade){
        printf("Error loading the classifier.");
	return 1;
    }

    /* setup the memory buffer for the face detector */
    storage = cvCreateMemStorage( 0 );
    if(!storage){
        printf("Error creating the memory storage.");
	return 1;
    }

    /* create a video window, auto size */
    cvNamedWindow(window_name, CV_WINDOW_AUTOSIZE);

    /* get a frame. Necessary for use the cvGetCaptureProperty */
    frame = cvQueryFrame(video);

    /* calculate the delay between each frame and display video's FPS */
    printf("%2.2f FPS\n", cvGetCaptureProperty(video, CV_CAP_PROP_FPS));
    delay = (int) (1000/cvGetCaptureProperty(video, CV_CAP_PROP_FPS));

    while (frame) {
	/* show loaded frame */
        cvShowImage(window_name, frame);
	
	/* wait delay and check for the quit key */
        key = cvWaitKey(delay);
        if(key=='q') break;
	/* load and check next frame*/
        frame = cvQueryFrame(video);
	if(!frame) {
		printf("error loading frame.\n");
		return 1;
	}

        /* detect faces */
        CvSeq *faces = cvHaarDetectObjects(
            frame, /* image to detect objects in */
            cascade, /* haar classifier cascade */
            storage, /* resultant sequence of the object candidate rectangles */
            1.1, /* increse window by 10% between the subsequent scans*/
            3, /* 3 neighbors makes up an object */
            0 /* flags CV_HAAR_DO_CANNY_PRUNNING */,
            cvSize( 40, 40 ) 
        );

        /* for each face found, draw a red box */
        for( i = 0 ; i < ( faces ? faces->total : 0 ) ; i++ ) {
             CvRect *r = ( CvRect* )cvGetSeqElem( faces, i );
             cvRectangle( frame,
                  cvPoint( r->x, r->y ),
                  cvPoint( r->x + r->width, r->y + r->height ),
                  CV_RGB( 255, 0, 0 ), 1, 8, 0 );
        }
    }
}

Yeah, I know the code needs a few adjustments. ¬¬

To compile it in a well configured OpenCV development environment:

gcc faceplayer.c -o faceplayer `pkg-config opencv ‑‑libs ‑‑cflags`

To run it you have to put in the same directory of the binary the XML classifier (haarcascade_frontalface_alt.xml) that comes with OpenCV sources at OpenCV-2.0.0/data/haarcascades/. And so:

./faceplayer video.avi

The results I got so far is that it works well for faces but sometimes its also detects more than faces. And here a video of it working live.

A example of good result:

rick roll face detection

A example of bad result:

rick roll face detection bad result

Maybe with some adjustments it could performs even better. But was really easy to create it using OpenCV.