Narendra Dhami

My Site

Archive for August, 2009

Complete Guide to Making Outlook Faster (Than Molasses)

Posted by Narendra Dhami on August 26, 2009


If you are stuck using Microsoft Outlook to send those TPS reports at work, you’ve already experienced just how painfully slow it can get—but with a few quick tips you can make it usable again. More …

Advertisements

Posted in Windows | Leave a Comment »

Automatic Face Detection in Photos with PHP

Posted by Narendra Dhami on August 20, 2009


Face Detection in Photos with PHP

I have always wondered how to detect faces automatically with php script. I have seen in many photo sharing and social network sites automatically detect a face and tag a name after being uploaded.

In this article, i will explain how possible this task can be achieved with simplicity with OpenCV and PHP Facedetect extension. Both are free to download and opensource.

Goal

To auto detect faces in a photo and draw pink box around the faces with a php script running a linux centos server. Please note that face detection and face recognition are two different things. To recognize a face you have to first detect a face and then do the required processing.

Requirements

– Linux server running Centos with SSH access

– PHP/Apache
– GD Library
– OpenCV [Download]
– PHP Facedetect extension [Download]

PHP facedetect extension is very simple. All you have to do is call a function face_detect(p) and it will give all the x,y coordinates in a photo where we draw a square. face_count() will output how many total faces in the given photo. For documentation see here

Installation

We install opencv and then we compile the php facedetect extension with php.

How to Install OpenCV

If you are running centos then one single line will install opencv.

yum install opencv

OpenCV may also need the following depencies to work properly and you will need to install them as well.

yum install ibpng libpng-dev zlib libjpeg libjpeg-dev libtiff libjasper swig python pkgconfig gtk gtk-dev

For more installation instructions on linux see here

The opencv will be installed in /usr/local/share/opencv and all the important facedetection training files known as “haar training” can be found in haarcascades folder in xml format (like haarcascade_frontalface_alt.xml)

How to test run OpenCV

Inorder to test run opencv you have to compile the samples folder. Go to /usr/local/share/opencv/samples/c/

Run this command to compile to binary.

./build_all.sh

If you find large number of errors and variables not declared like shown below..

Package opencv was not found in the pkg-config search path.
Perhaps you should add the directory containing `opencv.pc’
to the PKG_CONFIG_PATH environment variable
No package ‘opencv’ found
….

run

export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig
./build_all.sh

and then it will compile.

To test run the opencv run the following command in the c folder for a test.jpg photo.

./facedetect --cascade="../haarcascades/haarcascade_frontalface_alt.xml" test.jpg

Since your server does not have Xwindow installed, you probably do not see the output just the processing time.

If you see error “error while loading shared libraries: libcxcore.so.2: cannot open shared object file: No such file or directory” then see this solution

Install PHP Facedetect Extension

Installing the PHP facedetect extension is very easy. Just download the package and compile it for PHP.

wget
tar zxf facedetect-1.0.0

then

phpize && configure && make && make install

If you see phpize command not found error, install php developer libraries

yum install php-devel
OR
yum install php5-devel

then

open php.ini and make sure you add this line.

extension=facedetect.so

If facedetect has been successful, you will see this enabled in test.php.

facedet.PNG

Thats it! all the installation part is over!

Writing a PHP Script

Before you start writing php script make sure you copy all xml files in /usr/local/share/opencv/haarcascades folder to the web folder.

and this simple two lines to from php to call the function


<?php
//face_count() outputs total faces detected
// face_detect() outputs assoc array of x,y,width,height of each face recognized

$total= face_count('test.jpg','haarcascade_frontalface_alt.xml');
$coord= face_detect('test.jpg','haarcascade_frontalface_alt.xml');
print_r($coord);
?>

Make sure the path of xml files are correct else you would see a blank face or bool(false) output. Once you get this co-ordinates all we have to do is use php gd library to draw square around the face with the above coordinates.

This script will do that and you have call the script with photo file like this http://domain/face.php?file=test.jpg and the test.jpg file should be in the same folder


<?php
//face.php -> detects faces and draws a pink square on faces

function LoadJpeg($imgname)
{
    $im = @imagecreatefromjpeg($imgname); /* Attempt to open */
    if (!$im) { /* See if it failed */
        $im  = imagecreate(150, 30); /* Create a blank image */
        $bgc = imagecolorallocate($im, 255, 255, 255);
        $tc  = imagecolorallocate($im, 0, 0, 0);
        imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
        /* Output an errmsg */
        imagestring($im, 1, 5, 5, "Error loading $imgname", $tc);
    }
    return $im;
}

$total= face_count($_GET['file'],'haarcascade_frontalface_alt.xml');
$ord= face_detect($_GET['file'],'haarcascade_frontalface_alt.xml');

$im = LoadJpeg($_GET['file']);
$pink = imagecolorallocate($im, 255, 105, 180);

if(count($ord) > 0) {

foreach ($ord as $arr) {
imagerectangle($im,$arr['x'] ,$arr['y'] , $arr['x']+$arr['w'],
$arr['y']+$arr['h'], $pink);
}

}
header('Content-Type: image/jpeg');
imagejpeg($im);
imagedestroy($im);
?>

Just remember haarcascade_frontalface_alt.xml are haar training files used for face detection. You can play around with other training files like to detect various body parts, not just faces.

haarcascade_frontalface_alt.xml
haarcascade_frontalface_alt_tree.xml
haarcascade_fullbody.xml
haarcascade_profileface.xml
haarcascade_lowerbody.xml
haarcascade_upperbody.xml

Other Useful Links

Facedetection with pure PHP without OpenCV [visit site]
Facedetection with javascript [visit site]

OpenCV Face Detection Page [visit site]

Enjoy!

Original From http://corpocrat.com/2009/08/18/automatic-face-detection-with-php-in-linux/

Posted in PHP | Leave a Comment »

10+ Mod_Rewrite Rules You Should Know

Posted by Narendra Dhami on August 19, 2009


Mod_rewrite is an Apache-based rewrite engine for dynamically rewriting URLs. It’s built into Apache servers natively, though not enabled by default. It’s capable of functions beyond simple rewrites, though, some of which are included below. More …

Posted in Apache | Leave a Comment »

Really Useful Classes And Libraries For PHP Developers

Posted by Narendra Dhami on August 18, 2009


Today millions of websites and servers across the Internet are powered by PHP. Originally created by Rasmus Lerdorf in 1995 so that anyone can easily create a Personal Home Page; PHP has come a long way and is now widely used as general purpose scripting language that is suitable for majority of web development projects.

Numerous PHP Frameworks have evolved to enable rapid web development with PHP. However even greater number of standalone PHP libraries and classes are available which provide similar benefits. W3Avenue has compiled a list of some really useful classes and libraries that every PHP developers should be familiar with. Whether you like to use a PHP Framework or prefer to work without one, your productivity can multiply with the help of these libraries and classes. More …

Posted in PHP | Leave a Comment »

20 Interesting facts about PHP: A PHP developer should know

Posted by Narendra Dhami on August 11, 2009


Are you a PHP developer? Do you know all about PHP along with all these facts that I am presenting to you below? I bet you you don’t know at least 10 out of 20. You don’t believe me, lets read all 20 points below and find out how many of them you know already?

As a PHP developer you should know all these facts. I call them interesting because, almost all points surprised me. Though I am a PHP developer from the past 4 years but didn’t know all these facts.

1. PHP originally stood for Personal Home Page.
2. PHP which is now officially known as ‘Hypertext Preprocessor’ was released in the year 1995.
3. Initially written as a set of Common Gateway Interface (CGI) in ‘C’ (1994).
4. PHP was originally designed to replace a set of Perl scripts to maintain his Personal Home Pages (also known as PHP).
5. PHP was originally created by Rasmus Lerdorf in 1995. He wrote the original Common Gateway Interface (CGI) binaries.
6. Zeev Suraski and Andi Gutmans, two developers at the Technion IIT, rewrote the parser in 1997 and formed the base of PHP 3.
7. PHP 3 was official launched in June 1998.
8. Suraski and Gutmans rewrote the PHP 3’s core, producing the Zend Engine in 1999. They also founded Zend Technologies in Ramat Gan, Israel.
9. On May 22, 2000, PHP 4, powered by the Zend Engine 1.0, was released.
10. The main implementation of PHP is now produced by The PHP Group and serves as the de facto standard for PHP as there is no formal specification.
11. On July 13, 2004, PHP 5 was released, powered by the new Zend Engine II. PHP 5 introduced full featured object-oriented programming support. It was there in PHP 3 and PHP 4 but only the basic features.
12. PHP is free software released under the PHP License, which is incompatible with the GNU General Public License (GPL) due to restrictions on the use of the term PHP.
13. PHP was originally designed to create dynamic and more interactive web pages. It is the most widely-used, open-source and general-purpose scripting language.
14. It is possible to use PHP in almost every operating system. PHP can be used in all major operating systems including Linux, Microsoft Windows, Mac OS X, and RISC OS.
15. PHP uses procedural programming or object oriented programming and also a mixture of them.
16. PHP is installed on over 20 million websites and 1 million web servers.
17. 75% of Web 2.0 sites are built in PHP.
18. There are about 5 million PHP developers worldwide.
19. The latest release of PHP till now is 5.3.0. It was released on Jun 30, 2009. PHP 6 is under development alongside PHP 5. Major changes include the removal of register_globals, magic quotes, and safe mode. The reason for the removals was that register_globals had given way to security holes, and magic quotes had an unpredictable nature, and was best avoided.
20. Some of the biggest online brands, such as Facebook, ProProfs, Digg, Friendster, Flickr, Technorati, and Yahoo! are powered by PHP.

Posted in PHP | 3 Comments »

30 Useful PHP Classes and Components

Posted by Narendra Dhami on August 10, 2009


Simplicity and extensibility are the main reasons why PHP became the favourite dynamic language of the Web. In the last decade, PHP has developed from a niche language for adding dynamic functionality to small websites to a powerful tool making strong inroads into large-scale Web systems.

Below I present 30 useful PHP classes and components that you can use to test, develop, debug and deploy your PHP applications. Let me know if I missed anything or if you have something to add. More …

Posted in PHP | Leave a Comment »

20 Great non-PHP Tools for PHP Developers

Posted by Narendra Dhami on August 10, 2009


By nature I always strive to find more efficient, and better ways to perform tasks. There are a number of development tools that I use that really help me develop better applications in a reduced amount of time. These are the tools I use every day for web development. More …

Posted in General | Leave a Comment »

The Definitive Guide to htaccess Techniques: Do’s and Don’ts

Posted by Narendra Dhami on August 10, 2009


Of all the elements of web design and coding, htaccess can be one of the most intimidating. After all, it’s an incredibly powerful tool and one that has the potential to completely break your site if you’re not careful.

Below are a dozen basic htaccess techniques and tips to get you started. They’re not nearly as intimidating as many people expect, and if you study the code for a few minutes, I’m sure you’ll quickly grasp exactly how they work and why.

After that are a few bewares and don’ts for working with htaccess to help keep you out of trouble, and some more resources for further working with htaccess. More …

Posted in htaccess | 1 Comment »

INNODB Performance TODO List

Posted by Narendra Dhami on August 7, 2009


These are my plans for making InnoDB faster on SMP and high-IOPs servers. I think we can double throughput at high levels of concurrency.

Future work:

1. Reduce the size of mutex and rw-lock structures
2. Reduce contention on the sync array mutex
3. Reduce contention on kernel_mutex
4. Reduce contention on commit_prepare_mutex
5. Reduce the number of mutex lock/unlock calls used when a thread is put on the sync array
6. Name all events, rw-locks and mutexes in InnoDB to make contention statistics output useful
7. Add optional support to time all operations that may block
8. Introduce dulint to native 64-bit integer types
9. Make BUF_READ_AHEAD_AREA a compile-time constant
10. Prevent full table scans from wiping out the InnoDB buffer cache
11. Make prefetching smarter
12. Get feedback from Dimitri, Domas, Mikael and Percona
13. Use prefetch with MRR/BKA to get parallel IO in InnoDB
14. Investigate larger doublewrite buffer to allow for more concurrent IOs
15. Make Innodb work with a 4kb page size
16. Make trx_purge() faster when called by the main background thread
17. Use crc32 for Innodb page checksums with hardware support or otherwise make checksum faster.
18. Reduce the per-page overhead for sync objects
19. Repeat

Current work:

1. Add my.cnf options to disable InnoDB prefetch reads
2. Put more output in SHOW INNODB STATUS and SHOW STATUS
3. Reduce the overhead from buf_flush_free_margin()
4. Change background IO threads to use available IO capacity
5. Use more IO to merge insert buffer records when the insert buffer is full

Non-InnoDB work:

1. Fix mutex contention for the HEAP engine
2. Fix mutex contention for the MyISAM engine
3. Fix mutex contention for the query cache
4. Give priority (CPU, disk) to the replication SQL thread to minimize replication delay.
5. Push changes for –oltp-secondary-index to public sysbench branch
6. Add support to sysbench fileio for transaction log and doublewrite buffer IO patterns

Originally from http://mysqlha.blogspot.com/2009/05/innodb-performance-todo-list.html

Posted in MySQL | Leave a Comment »

Setting up MySQL Asynchronous Replication for High Availability

Posted by Narendra Dhami on August 7, 2009


MySQL replication is often positioned as a solution to provide extra throughput for your database (especially when dealing with high numbers of read operations). What tends to be overlooked is how it can be used to provide high availability (HA) – no matter how much redundancy you have at a local level, your system remains at risk from a single catastrophic failure – loss of power, earthquake, terrorist attack etc. By using MySQL asynchronous replication to maintain a geographically remote copy of that data, service can be maintained through any single site failure.

As this replication is asynchronous, there are no low latency demands on the network and so the two sites can be thousands of miles apart while utilising low-cost connections.

This article provides a simple example of how to set up asynchronous replication between 2 MySQL databases in order to provide a Highly Available solution. First of all, it will be 2 databases where the tables will be stored in the MyISAM storage engine and then between 2 MySQL Cluster databases where I also configure it for Multi-master replication where changes can be made at either site. More …

Posted in MySQL | Leave a Comment »