Hiển thị các bài đăng có nhãn Install Software on Ubuntu. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn Install Software on Ubuntu. Hiển thị tất cả bài đăng

3/5/14

Ubuntu Stuff


I've got two ubuntu systems now, both very clean and straight forward setups. No hardware hassling, which is amazing IMHO, after coming from years of redhat. Here's some notes for setting up both systems, which some may find useful:




    Ubuntu 8.04 on an Intel Mac Mini

    I like using linux for my main workstation, and since Mac Mini's are quiet and small, I transitioned from an intel tower to the Mac Mini; was quite smooth. Installing was no problem; put the regular intel Ubuntu 8.04 DVD into the Mac Mini's drive, reboot and install.Here's some extra info bringing up the Mac Mini from a newly bought system.

    Ubuntu 8.04 Install Details

    First time setting up linux on an intel mac mini.. no problem. Never once booted OSX, or needed to. Turned on machine with regular Intel Ubuntu CD in drive, Hold down ALT key on mac keyboard to boot the CD.
    Easy install.. no tricks. Just normal intel install on the mac mini's internal drive.

    Ubuntu 8.04 Post-Install

    After reboot into OS:
      1) 'apt-get update' to update the apt-get database.2) Used 'network-admin' to:
                  * Setup static IP, hostname, removed '127.0.0.1 tahoe' entry from /etc/hosts
                  * Setup DNS and gigabit router
                  * Disable wireless et al.
              
      3) Installed NFS so that my local tools (like 'admlog') will work:
                 1a) apt-get install nfs-common
                 1b) Tweaked /etc/exports on file server to allow exports to new machine
                 1c) Added to /etc/fstab:
                     192.168.1.14:/net /meade/net nfs intr,hard,bg,rw,nolock,vers=3 0 0
                 1d) mount /meade/net
              
      4) Some aliases for root's login to use my local network tools (tweaked /root/.profile):
                  admlog() {
                      /net/bin/admlog $*
                  }
      
                  piss() {
                      /net/bin/piss $*
                  }
                  
      5) Started installing necessary stuff:
                      apt-get install tcsh
                      apt-get install gpm                 -- console copy/paste..!
                      apt-get install ssh                 -- sshd
                      apt-get install vim                 -- replaces 'vim-tiny'
                      apt-get install gawk                -- for 'piss'
                      apt-get install rdate
                  
      6) Installed necessary dev stuff:
                      apt-get install g++
                      apt-get install manpages-dev        -- don't forget the man pages!
                      apt-get install subversion          -- aka svn
                      apt-get install libx11-dev
                      apt-get install libxt-dev
                      apt-get install libxft-dev
                      apt-get install valgrind
                      apt-get install libglut3-dev        -- gets opengl, glut, etc
                      apt-get install doc-linux-html      -- /usr/share/doc/HOWTO
                  
      Optional dev stuff important for me:
                      apt-get install indent
                      apt-get install xxdiff
                      ln -s /usr/bin/xxdiff /usr/bin/xdiff
                  
      7) Disable X windows on boot
      Yeah, I like my own window manager, and like to start it manually, and not have X come up automatically.
      OK, init is completely different now, you can't just change run levels.
                 mv /etc/X11/default-display-manager /etc/X11/default-display-manager.bak
                 echo false > /etc/X11/default-display-manager
                 
      ..and then to stop it:
                 /etc/init.d/gdm stop
                 
      8) Installed chkconfig. Well, found 'rc-config' anyway on the web, which is close enough.
      9) Started making myself at home:
                  chsh /bin/tcsh          -- for erco and root
      
                  rcp -rp on:/usr/local/src/fltk-1.3.x-svn /usr/local/src/fltk-1.3.x-svn
                  rcp -rp on:/usr/local/src/flwm /usr/local/src/flwm
                  rcp on:/usr/local/bin/nixieclock /usr/local/bin/
                  
      10) Removed weird thai/malaysian/indian/arabic fonts that were crowding up my gimp font browser with too much noise:
                  apt-get remove ttf-arabeyes
                  apt-get remove ttf-lao 
                  apt-get remove ttf-malayalam-fonts 
                  apt-get remove ttf-thai-tlwg
                  apt-get remove ttf-indic-fonts-core
                  
      Got the list of installed fonts by running:
                  aptitude search '~i' | grep font
                  
      11) Various other stuff:
                  apt-get install mplayer
                  apt-get install xpdf
                  apt-get install mpage
                  apt-get install dict
                  apt-get install xvncviewer              -- 'vncviewer' (yes, unauth'ed)
                  apt-get install imagemagick
                  aptitude install desktop xfce-desktop   -- small desktop (I use FLWM, but tried this just for fun)
                  apt-get install kompozer
                  apt-get install lame                    -- mpg conversion
                  
      And after all that, I was pretty happy.

    Printing

    For linux tools like gimp and firefox 3 to recognize the laser printer on my Mac, had to configure linux printing with:
      1) Run: system-config-printer2) Click 'Server Settings' from browser
      3) Enable the 'Show printers shared by other systems'
      4) Then 'Apply'.
    Now 'gimp' and firefox3 will show the tower printers in the choosers.

    Firefox Tweaks

    firefox 3 -- middle clicking to 'paste' a link no longer works. Had to enable it:
            1) about:config
            2) Double click on "middlemouse.contentLoadURL" to change "false" to "true"
        

    Installed acrobat

    Downloaded latest, ran INSTALL program:

      1) At the "Enter installation directory for Adobe Reader 8.1.3 [/opt]" prompt, specified:
                 /usr/local
                 
      ..which creates "/usr/local/Adobe/..."2) ln -s /usr/sbin/acroread /usr/local/bin/acroread
      Note that acroread's shell script handles a lot of weird flags (-version, -display..).
      3) That's it -- firefox viewing PDF files will open WITHIN the browser.
      To change firefox to open acroread as a separate window:

        a) Run 'acroread'b) Click Edit > Preferences > Internet
        c) Deselect 'Display PDF In Browser Using [Acrobat application]
        d) Click OK
      Reference: http://kb.adobe.com/selfservice/viewContent.do?externalId=333563

    Flash Player Install

    Trouble installing flash playerAfter installing, it would not load up into firefox. Was getting errors about libnss3.so not being found.
    SOLUTION:

      Had to manually create several symlinks:
              ln -s /usr/lib/libnss3.so.1d /usr/lib/libnss3.so
              ln -s /usr/lib/libnspr4.so.0d /usr/lib/libnspr4.so
              ln -s /usr/lib/libplds4.so.0d /usr/lib/libplds4.so
              ln -s /usr/lib/libplc4.so.0d /usr/lib/libplc4.so
              

    Configured rdate to slam clock every 12 hours to network timekeeper

    Sorry, but after years of dicking with ntp, I've decided its more trouble than it's worth. Went back to good ol rdate which has worked reliably for many years, and I'm fine with it. Configured new machine with rdate:55 0,12 * * * root /usr/bin/rdate -s -l -p meade >> /var/log/rdate.log 2>&1

    Installing Maya 2009

    Found that Maya 2009 'setup' program needs to have:
            1) rpm
            2) bash
        
    So:
            apt-get install rpm
            apt-get install bash
        
    Then, regular maya install.

    RSH Setup


            1) Install inetd
    
                    apt-get install inetutils-inetd
    
            2) Install rsh server + client:
    
                    apt-get install rsh-server
                    apt-get install rsh-client
    
            3) echo + > /root/.rhosts
               chmod 600 /root/.rhosts
    
            4) Modify this line in /etc/pam.d/rsh to allow "+" to work:
    
        BEFORE: auth    required        pam_rhosts_auth.so
         AFTER: auth    required        pam_rhosts_auth.so promiscuous
    
            5) Restart inetd
              /etc/init.d/inetutils-inetd restart
    
            6) rsh localhost ls
        

    Installed doxygen

        1) Just ran:
    
               apt-get install doxygen
    
           This will at least generate html and latex docs.
    
           Downloaded the PDF docs from their website, and copied it into
           /usr/share/doc/doxygen (because it doesn't seem to come with..!)
    
        2) You may want 'pdflatex' to generate the latex docs into a pdf file.
           (You'll find the Makefile in the documentation/latex/ directory wants this)
    
           To install pdflatex:
    
               apt-get install texlive
        

    Installed sox for sound recording

            apt-get install sox
            apt-get install libsox-fmt-oss      -- needed for oss + /dev/dsp to work
    
        Test recording from audio input:
    
            sox -w -c 2 -r 44100 -t oss -s /dev/dsp /var/tmp/foo.wav
        



Ubuntu 7.04 on HP Pavilion dv2000 Notebook

A few months ago (Fall 2007), got an "HP Pavilion dv2000" notebook computer, and installed Ubuntu 7.04 on it. Nice light machine, and pretty cost effective.Install was smooth/default. Only odd things I noticed:

  • Apparently the csh/tcsh is not preinstalled on Ubuntu. Had to apt-get it, since I prefer the csh for my login shell, instead of bash. Kinda weird, since every Unix release I've ever encountered since the early 90's always included a csh.. sun, freebsd, sgi/irix, linux distros. Ubuntu's the first that didn't include a csh!
  • The dv2000's onboard ethernet apparently is not gigabit.I then made the mistake of thinking "I'll just get a gigabit PCMCIA card", but when I tried to install it, found the HP dv2000 does not have a PCMCIA slot..! That thing that *looks* like a PCMCIA slot is actually an ExpressCard slot. So no go for PCMCIA on this thing.
    So I bought a "TRENDnet TU2-ETG" USB gigabit ethernet dongle (very cheap), which Ubuntu 7.04 automatically recognized as eth2, and was able to easily enable by just running "network-admin" from the command line, assigning it an IP address, and un-checking the onboard eth0 to disable that. After rebooting, the USB gigabit was up and running happily.
  • There are continuous complaints on the console and /var/log/messages about:bcm43xx: Error: Microcode "bcm43xx_microcode5.fw" not available or load failed.
    Apparently the easy solution for this is to blacklist the module from trying to load, but I haven't bothered. (Update: it is now December 2009, and these messages are still happening, but I've been ignoring them)
  • Disappearing mouse.Possibly caused by switching virtual consoles (ctrl-alt-f1, etc), the X server's mouse would sometimes disappear.
    When booting into our custom runlevel 3 (x windowless), starting flwm would have no mouse. Sometimes even ubuntu's defaults would do the same. This page seemed to have the fix:
    https://bugs.freedesktop.org/show_bug.cgi?id=3009
    ..explaining it as a driver bug caused by the hardware mouse cusor default. By setting the cursor to software, it works around the problem.
    Made following ("HWCursor" "off") change to /etc/X11/xorg.conf:
             Section "Device"
                    Identifier  "nVidia Corporation C51 [Geforce 6150 Go]"
                    Driver              "nv"
                    BusID               "PCI:0:5:0"
                    #ERCO: DISABLE HARDWARE CURSOR -- sometimes disappears!
                    Option              "HWCursor"              "off"
             EndSection
             
  • X11 enable TCP portTo allow remote X11 access, modified /etc/X11/gdm/gdm.conf
             before: DisallowTCP=true 
              after: DisallowTCP=false
             
  • I happened to read this article on slashdot:
    Ubuntu May Be Killing Your Laptop's Hard Drive http://hardware.slashdot.org/article.pl?sid=07/10/30/1742258Indeed, my system had this problem of an 'over agressive power saving feature", as shown by the HD's "Load_Cycle_Count" increasing at a steady rate:
    smartctl -d ata -a /dev/sda | grep Load_Cycle_Count
    ..so I took those steps to fix it, but forgot to document it properly, but I think it just involved adding 'hdparm -B 255' or some such. Grepping the /etc/ directory, looks like I created these:
              --- /etc/acpi/resume.d/99-hdd-spin-fix.sh
                  #!/bin/sh
                  hdparm -B 255 /dev/sda
    
              --- /etc/acpi/start.d/99-hdd-spin-fix.sh
                  #!/bin/sh
                  hdparm -B 255 /dev/sda
    
              --- /etc/acpi/suspend.d/99-hdd-spin-fix.sh
                  #!/bin/sh
                  hdparm -B 255 /dev/sda
    
              
    See also: http://halojetter.blogspot.com/2007/10/ubuntu-not-killing-your-laptops-hard.htmlAlso, I may have disabled laptop power saving mode:
              # grep LAPTOP /etc/default/acpi-support
              ENABLE_LAPTOP_MODE=false              <-- off
              
    All else seems well with Ubuntu 7.04 on the HP Pavilion dv2000 so far. It's been getting heavy use the last month or so.



Useful apt-get commands

A collection of useful apt-get commands..
                                     UBUNTU: APT-GET/DPKG              REDHAT: SIMILAR RPM COMMAND
                                     -------------------------------   -------------------------------------------
             Searching for packages: apt-cache search some_string      http://rpmfind.com/, etc
                  Show Package Info: apt-cache showpkg xxx             rpm -qpi /tmp/foo.rpm
          Show Package Dependencies: apt-cache depends xxx             
                            Install: apt-get install xxx               rpm -ivh /tmp/foo.rpm
                         Re-Install: apt-get --reinstall install xxx   rpm -ivh -force /tmp/foo.rpm
                             Remove: apt-get remove xxx                rpm -e pkgname
    Remove everything (configs too): apt-get --purge remove xxx
                            Upgrade: apt-get -u upgrade
                      Show upgrades: apt-show-versions -u
        Show All Installed Packages: dpkg --list                       rpm -qa

        Find package given filename: apt-file search /bin/ping         rpm -qf /bin/ping
        Find filenames in a package: apt-file list xxx                 rpm -ql pkgname, rpm -qpl /tmp/foo.rpm
        Updating the apt-file cache: apt-file update

                *** SOURCE PACKAGES ***
        Getting source packages: apt-get source xxx
                  Build package: apt-get -b source packagename         rpm -ba, rpm-build -ba /tmp/foo.rpm
  Building Package Dependencies: apt-get build-dep xxx

12/2/13

Tạo và chạy ứng dụng Android đầu tiên với Eclipse


Tạo và chạy ứng dụng Android đầu tiên với Eclipse

Ở bài số 1 chúng ta đã học cách cài đặt và cấu hình môi trường lập trình Android trên IDE Eclipse. Các bạn có thể tham khảo bài trước ở đây
Bước 1: Chọn New Android App Project , xuất hiện hộp thoại sau:
Build SDK: mặc định là bản latest SDK bạn đã cái trên máy
MinimumRequired SDK: bản thấp nhất của Android hỗ trợ cho app của bạn

Bước 2: Tạo icon cho ứng dụng
Tham khảo http://developer.android.com/design/style/iconography.html
Bước 3: Chọn template cho project, với VD này là Blank Activity
Bước 4: Chọn next ở màn hình tiếp theo, nếu gặp màn hình này chọn Install/Upgrade
Chọn “Accept” và “Install”
Sau khi upgrade xong , ấn “Finish” và khởi động lại Eclipse
Một vài chú ý trước khi chạy project:
AndroidManifest.xml mô tả những đặc tính cơ bản và xác định các thành phần của ứng dụng. Bạn sẽ được học rõ hơn trong những bài tiếp theo.
Src: folder chính để lưu giữ các fie mã nguồn. Mặc định nó bao gồm lớp Activity sẽ được gọi khi khởi chạy ứng dụng
Res: chứa những thư mục con để lưu trữ hình ảnh âm thanh của ứng dụng
drawable-hdpi/
Thư mục cho các đối tượng drawable( chẳng hạn như ảnh bitmap) được thiết kế mật độ cao (hdpi). Các thư mục drawable khác chứa tài sản được thiết kế cho các mật độ màn hình khác.
layout/
Thư mục định nghĩa giao diện người dùng cho ứng dụng của bạn
values/
Thư mục cho các tập tin XML để định nghĩa màu sắc và chuỗi ký tự.
Trước khi chạy chúng ta phải thiết lập máy ảo như sau:
Chọn biểu tượng ở thanh toolbar, hộp thoại hiện lên chọn New, sau đó nhập một vài thông số:
Name: Tùy ý
Targert:  Chọn phiên bản hệ điều hành bạn muốn
SD Card: gõ size của SD Card ( mình để là 256 MiB)
Skin: Có thể để default (HVGA) hoặc chọn kích cỡ bạn muốn
Sau khi khởi tạo máy ảo chọn máy ảo và nhấn nút Start ở thanh công cụ bên phải. Giao diện sau khi chạy thành công

Quay lại với project MyFirstApp đã tạo ở bước trên, chọn và click Run từ thanh toolbar
Một số chức năng quan trọng cần biết khi lập trình Android
Android có một hệ thống debug hoàn hảo được hỗ trợ bởi logcat. Logcat sẽ thông báo toàn bộ về hệ điều hành, giúp chúng ta biết được  hệ điều hành đang làm gì, gọi đến cái gì, khởi chạy những gì, chiếm dụng bộ nhớ ra sao … (các bạn sẽ được nói rõ hơn trong những bài sau)

File Explorer của Android là tính năng hữu ích của Google đưa vào giúp chúng ta quản lý file trong sd card  và cả file system data. File Explorer giúp bạn dễ dàng đưa file vào/ lấy file ra trong sdcard ảo của simulator, xóa cơ sở dữ liệu để khởi tạo lại (only emulator)
Mở File Explorer bằng cách: Window->ShowView->Other->Android->File Explorer

19/11/12

Stardict tren Ubuntu


gnome2-globalmenu ( thanh panel giong MacOS)

Terminal:
deb http://ppa.launchpad.net/globalmenu-team/ppa/ubuntu jaunty main
deb-src http://ppa.launchpad.net/globalmenu-team/ppa/ubuntu jaunty main
sudo apt-get update
sudo apt-get install gnome-globalmenu
Links: http://code.google.com/p/gnome2-globalmenu/wiki/InstallingonUbuntu

Stardict tren Ubuntu

1. Cai Stardict:(Gom 2 goi stardict va stardict-plugin
sudo apt-get install stardict stardict-plugin
=
sudo apt-get install stardict
va
sudo apt-get install stardict-plugin

2. Cai cac bo tu dien:(vi du theo link nay: http://stardict.sourceforge.net/Dictionaries_misc.php), no la file (*.rpm)
3. Cai goi alien: => De convert file(*.rpm)-->file(*.deb):
$sudo apt-get update 
$sudo apt-get install alien

4. Cach convert file(*.rpm)-->file(*.deb):
a) Chuyen den thu muc chua file (*.rpm) vua down ve:
Vi du:
$cd ~/Desktop (Vidu: cd /home/pht/Desktop) 
b) Bat dau convert file (*.rpm) sang (*.deb):
$sudo alien -k name-of-rpm-file.deb (Vidu: ~/Desktop$ sudo alien -d stardict-dictd_anh-viet-2.4.2-1.noarch.rpm) 

7/1/12

Introduction to Computer Vision with the OpenCV Library on Linux

1. Abstract

The purpose of this document is to help a reader to get started with Computer Vision library OpenCV on Linux system. OpencCV is a multi-platform library, but this article will be focused only on OpenCV using Linux operating system ( although, just the installation of the OpenCV library and video camera is platform-specific, all examples in this article should compile on any platform where OpenCV is properly installed such as  Mac OS, MS Windows and etc.).  Reader will be guided through a step-by-step guide on how to install and use some of the basic functions of OpenCV library such as displaying images, playing a video or using a video camera to process a video input stream.
Conventions used in this article:
  • $ - execution on the command line by a non-privileged user
  • # - execution on the command line by a superuser
  • the actual command to be executed on the command line or code of program to be compiled
  • OUTPUT: output produced on the command line by command execution
  • NOTE: general notes and additional information

2. Introduction

In simple words a Computer Vision is a scientific field which attempts to provide a sight to the machine. This scientific field has expanded rapidly in recent years. Among researchers this growth is because of many improvements of vision algorithms and among the computer vision hobbyists this is due to the cheaper hardware components and processing power.  OpenCV library plays a great role in the Computer Vision field as it helps greatly to reduce cost and preparation time of computer vision research environment needed by university students, hobbyists and professionals. OpenCV also provides a simple to use functions to get the work done in a simple, effective and elegant manner.  OpenCV was started by Intel, and later it was transformed to an open source project now available on SourceForge.net. OpenCV library has multi-platform availability,  and it is partially written in C++ and C language. Despite the fact that this library is available on many Linux distributions from its relevant package repositories, in this article we will attempt to install and use OpenCV library compiled from a source code downloaded from SourceForge.net web site.


The reasons for compiling a source code may include:
  • new version 2.0.0 recently released and more features available
  • some bugs fixed which affected Linux OpenCV 1.0.0 versions ( such as cvGetCaptureProperty() etc. )
  • more support is available for OpenCV 2.0.0 version than for former 1.0.0 version
This article will start with installation of OpenCV on Debian 5.0 ( Lenny ). Later a reader will be guided through a number of examples on how to use OpenCV to display an image, play a video and use camera to capture the video input stream.

3. Installation

The following section will describe an installation process of OpenCV library by building a binaries from a source code available from SourceForge.net. The installation procedure demonstrated here was tested on Debian 5.0 ( Lenny ) and Ubuntu 9.10 ( Karmic Koala ). The actual installation procedure should be similar or exactly same for most Linux distributions apart of the first step where package dependencies are installed from relevant Debian and Ubuntu distribution repositories. On RPM linux system you sould consult your Red Hat package management ( RPM ) tool for alternatives to OpenCV prerequisites described in the next section.

3.1. Prerequisites

First, what needs to be done is the installation of required prerequisites required by OpenCV library. The list of dependencies can be slightly modified according to your needs:
  • libavformat-dev - development files for libavformat the ffmpeg file format library
  • libgtk2.0-dev - development files for the GTK+ graphical user interface library
  • pkg-config - manage compile and link flags for libraries
  • libswscale-dev - development files for libswscale the ffmpeg video scaling library
  • cmake - A cross-platform, open-source make system used for compilation of source code
  • bzip2 - high-quality block-sorting file compressor used to extract OpenCV source file
The following command will automatically fetch and install all required packages and its dependencies:
# apt-get install libavformat-dev libgtk2.0-dev pkg-config cmake libswscale-dev bzip2

3.2. Obtaining OpenCV source code

Current version of OpenCV library at the time of writing is a version 2.0.0. You can download an OpenCV source code by pointing your web browser to OpenCV-SourceForge.net or use the wget command to acquire a source code directly on the command line:
$ wget http://downloads.sourceforge.net/project/opencvlibrary/opencv-unix/2.0/OpenCV-2.0.0.tar.bz2

3.3. Extract OpenCV source code

Whether you used web browser or wget utility to download source code of OpenCV library you should end up with OpenCV-2.0.0.tar.bz2 tarball in your current working directory. The next step is to extract source files with the tar command. The following command will extract all files into OpenCV-2.0.0 directory:
$ tar xvjf OpenCV-2.0.0.tar.bz2
New OpenCV-2.0.0 directory ( approx. 67MB ) should be now available in your current working directory and will contain all necessary source files for a compilation.

3.4. Compilation and installation of OpenCV binaries

To compile OpenCV source code, we are going to use an open-source make system cmake. The following cmake configuration compile flags are going to be set:
  • CMAKE_BUILD_TYPE=RELEASE : cmake will bulid a release project
  • CMAKE_INSTALL_PREFIX=/usr/local : directory to be used as a installation destination
  • BUILD_PYTHON_SUPPORT : enable python support
NOTE: cmake utility by default does not provide a way to uninstall your project from a system. If you have a need to uninstall OpencCV from you system you should make appropriate changes before you proceed with compilation.  

Navigate to OpenCV-2.0.0 directory containing a source code:
$ cd OpenCV-2.0.0/
Create and navigate to a new directory to be used by cmake. I this case, the directory name is same as project type, "release":
$ mkdir release; cd release
Use cmake to create a configuration files with configuration flags described above:
NOTE: CMAKE_INSTALL_PREFIX flag can be set to any desired installation path
cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D BUILD_PYTHON_SUPPORT=ON ..
After execution of the cmake command the installation summary will by displayed and will look similar to the one below.
OUTPUT:
-- General configuration for opencv 2.0.0 =====================================
--
--     Compiler:
--     C++ flags (Release):         -Wall -pthread -ffunction-sections  -O3 -DNDEBUG  -fomit-frame-pointer -O3 -ffast-math -mmmx -DNDEBUG
--     C++ flags (Debug):           -Wall -pthread -ffunction-sections  -g  -O0 -DDEBUG -D_DEBUG
--     Linker flags (Release):
--     Linker flags (Debug):
--
--   GUI:
--     GTK+ 2.x:                  1
--     GThread:                   1
--
--   Image I/O:
--     JPEG:                      TRUE
--     PNG:                       TRUE
--     TIFF:                      FALSE
--     JASPER:                    FALSE
--
--   Video I/O:
--     DC1394 1.x:                0
--     DC1394 2.x:                0
--     FFMPEG:                    1
--       codec:                   1
--       format:                  1
--       util:                    1
--       swscale:                 1
--       gentoo-style:            1
--     GStreamer:                 0
--     UniCap:
--     V4L/V4L2:                  1/1
--     Xine:                      0
--
--   Interfaces:
--     Old Python:                0
--     Python:                    ON
--     Use IPP:                   NO
--     Build Documentation        0
--
--     Install path:              /usr/local
--
--     cvconfig.h is in:          /home/sandbox/OpenCV-2.0.0/release
-- -----------------------------------------------------------------
--
-- Configuring done
-- Generating done
-- Build files have been written to: /home/sandbox/OpenCV-2.0.0/release

When the execution of cmake command did not produce any errors, then we are ready to compile a source code.:
NOTE: There will be a number of warning messages shown on your terminal during a build process. These warning messages can be ignored, unless they do affect your preferred OpenCV environment settings!
$ make
If no errors were displayed on the terminal and the progress dialog reached [100%] during the build process, we are ready to install OpenCV libraries. The installation is optional as long as your environmental variable LD_LIBRARY_PATH is linked to an appropriate OpenCV built directory. If you wish to install OpenCV into /usr/local as set by cmake flags above, execute a following command:
# make install
Export correct path to LD_LIBRARY_PATH environment variable and use ldconfig to dynamically link to an OpenCV library:
$ export LD_LIBRARY_PATH=/usr/local/lib/:$LD_LIBRARY_PATH
# ldconfig
If you do not wish to install OpenCV library you should just export a correct path to OpenCV library build directory to let your system know where the library is located. Suppose that your new release directory is located at ~/OpenCV-2.0.0/release then your export path will look like this:
$ export LD_LIBRARY_PATH=~/OpenCV-2.0.0/release/:$LD_LIBRARY_PATH
# ldconfig
This completes an installation procedure of OpenCV library. For additional information in regard to the OpenCV installation visit OpenCV install guide.

4. OpenCV examples

Without prolonging a discussion about what Computer vision is and how it is related to OpenCV we will now move right to some examples on how to write, compile and execute simple programs using OpenCV library. If you are interested in a more intense introduction to Computer Vision and OpenCV I recommend a book: "Learning OpenCV: Computer Vision with the OpenCV Library by Gary Bradski and Adrian Kaehler".

An Image conversion

Let's start with something really simple and that is 7 lines of code to convert image between following image types:
  • Windows bitmaps - BMP, DIB
  • JPEG files - JPEG, JPG, JPE
  • Portable Network Graphics - PNG
  • Portable image format - PBM, PGM, PPM
  • Sun rasters - SR, RAS
  • TIFF files - TIFF, TIF
The following program will accept two command line arguments, source image and destination image. Source image will be stored as an image type specified by destination image file extension. Save the following code in a file called image-conversion.c :
#include "highgui.h"

int main( int argc, char** argv ) {
    IplImage* img = cvLoadImage( argv[1]);

    cvSaveImage( argv[2] , img);
    cvReleaseImage( &img );
return 0;
}
Source code of our new program is ready and here comes the compilation part. Assuming that you have saved your first OpenCV program as image-conversion.c you can compile your program with the following command:
$ g++ `pkg-config opencv --cflags --libs` image-conversion.c -o image-conversion
After successful compilation a new executable binary file named image-conversion is created in your current working directory. Before we test this new program, we need some sample image:
$ wget -O image.png http://www.linuxconfig.org/templates/rhuk_milkyway/images/mw_joomla_logo.png
wget downloaded and saved an image image.png into your current directory, and we can now attempt to convert this image to any image type listed above. The following command will convert image type PNG to JPG. Assuming that program compilation did not produce any errors and your binary file is saved as image-conversion you can convert between two image types with following command:
$ ./image-conversion image.png image.jpg
To confirm that image was converted, a file command can be used to display a file type for a given file as an argument:
$ file image.*
OUTPUT:
image.jpg: JPEG image data, JFIF standard 1.01
image.png: PNG image, 270 x 105, 8-bit/color RGBA, non-interlaced
When you look at the compilation command once more you can observe that a pkg-config utility had been used to retrieve a location of an OpenCV library with the use of --cflags option as well as to get all dependencies using --libs option. Therefore, an alternative command to the one above without pkg-config utility can be constructed to look something like this:
g++ -I/usr/local/include/opencv -L/usr/local/lib \ 
-lcxcore -lcv -lhighgui -lcvaux -lml image-conversion.c -o image-conversion
However, in both cases the compilation command will create unwanted library dependencies:
$ ldd image-conversion | grep local
OUTPUT:libcxcore.so.2.0 => /usr/local/lib/libcxcore.so.2.0 (0xb7ccc000)
libcv.so.2.0 => /usr/local/lib/libcv.so.2.0 (0xb7a7a000)
libhighgui.so.2.0 => /usr/local/lib/libhighgui.so.2.0 (0xb7a3f000)
libcvaux.so.2.0 => /usr/local/lib/libcvaux.so.2.0 (0xb793b000)
libml.so.2.0 => /usr/local/lib/libml.so.2.0 (0xb78d8000)

Our program is dependent on OpenCv's highgui.h library and therefore including -lcvaux -lml -lcxcore and -lcv dependencies into a compilation command is not necessary. A shortened version of compilation command will look like this:
$ g++ -I/usr/local/include/opencv -lhighgui image-conversion.c -o image-conversion
Consequently, a program library dependency had been reduced:
$ ldd image-conversion | grep local
OUTPUT:
libhighgui.so.2.0 => /usr/local/lib/libhighgui.so.2.0 (0xb7f61000)
libcxcore.so.2.0 => /usr/local/lib/libcxcore.so.2.0 (0xb7a75000)
libcv.so.2.0 => /usr/local/lib/libcv.so.2.0 (0xb7823000)

From now on, it is up to you how you compile following examples in this article. Keep in mind that the first compile command including pkg-config will be able to compile all examples. However, it may produce a binary with excessive dependencies.

4.1. Display an Image

At this point, we have been able to convert an image type and confirm its meta description by file command. It is time to display an image on the screen and visually confirm that it was converted correctly.  The following example program will display an image on the screen:
#include "highgui.h"

int main( int argc, char** argv ) {
// cvLoadImage determines an image type and creates datastructure with appropriate size
    IplImage* img = cvLoadImage( argv[1]);

// create a window. Window name is determined by a supplied argument
    cvNamedWindow( argv[1], CV_WINDOW_AUTOSIZE );
// Display an image inside and window. Window name is determined by a supplied argument
    cvShowImage( argv[1], img );
// wait indefinitely for keystroke
    cvWaitKey(0);

// release pointer to an object
    cvReleaseImage( &img );
// Destroy a window
    cvDestroyWindow( argv[1] );
}
NOTE: Return to an image conversion section above, if you need help on how to compile this OpenCV program.
Execution of this display-image program with an image.jpg produced in preceding section will display this image on the screen:
$ display-image image.jpg
OUTPUT:

4.2. Gaussian smooth

You can also attempt to create a simple image transformation using the gaussian smooth method. Add a following line into your display-image code before a cvShowImage function call:
...

cvNamedWindow( argv[1], CV_WINDOW_AUTOSIZE );

cvSmooth( img, img, CV_GAUSSIAN, 9, 9 );

cvShowImage( argv[1], img );
...
and add as a first line to your program ' #include "cv.h" ' directive.

This will incorporate a gaussian smooth method centered on each pixel with 9 x 9 area into the output image. After compilation and execution a following output will be presented:
OUTPUT:

opencv gaussian smooth

4.3. Play video

This section includes a program code which will create a simple video player using OpenCV library. Sample video, tree.avi can be found in your OpenCV-2.0.0 directory where you have extracted its source files ( OpenCV-2.0.0/samples/c/tree.avi ) :
#include "cv.h"
#include "highgui.h"

// initialize global variables
int g_slider_position = 0; // trackbar position
CvCapture* g_capture = NULL; // structure to create a video input

// routine to be called when user moves a trackbar slider
void onTrackbarSlide(int pos) {
  cvSetCaptureProperty(
  g_capture,
  CV_CAP_PROP_POS_FRAMES,

  pos
  );
}

int main( int argc, char** argv ) {

// create a window with appropriate size. Windows name is determined by file name
// supplied as an argument
cvNamedWindow( argv[1], CV_WINDOW_AUTOSIZE );
// open video
g_capture = cvCreateFileCapture( argv[1] );
// set read position in units of frames and retrieve total number of frames
int frames = (int) cvGetCaptureProperty(

  g_capture,
  CV_CAP_PROP_FRAME_COUNT
);


// do not create treackbar if video does not include an information
// about number of frames
if( frames!=0 ) {

  cvCreateTrackbar(
  "Position",
  argv[1],
  &g_slider_position,
  frames,

  onTrackbarSlide
  );
}

// display video frame by frame
IplImage* frame;
while(1) {

frame = cvQueryFrame( g_capture );
if( !frame ) break;
cvShowImage( argv[1], frame );
// set trackbar to a current frame position
cvSetTrackbarPos("Position", argv[1], g_slider_position);

g_slider_position++;

char c = cvWaitKey(33);
// quit if ESC is pressed
if( c == 27 ) break;

}
// free memory
cvReleaseCapture( &g_capture );
cvDestroyWindow( argv[1] );
return(0);
}
NOTE: Return to an image conversion section above, if you need help on how to compile this OpenCV program.
Execute your new OpenCV program and as an argument supply a video file:
$ ./video-player ~/OpenCV-2.0.0/samples/c/tree.avi
OUTPUT:
example opencv video programm

4.4. Input from a video camera

The aim of this section is to provide some simple tips on how to configure a camera on a linux system and how to confirm that your video camera is recognized by your system correctly. When your camera is ready, you will be presented with a simple program which is capable to display a video using a video camera as an input.

For this article I have used a  Logitech, Inc. QuickCam Pro 9000 camera. Installation of this camera on Debian 5.0 or Ubuntu 9.10 ( Karmic Koala ) system was simple Plug & Play procedure.  Here are some hints on how to confirm that your camera had been recognized by your system:

NOTE:
your output will be different !
$ lsusb
OUTPUT:
Bus 002 Device 003: ID 046d:0990 Logitech, Inc. QuickCam Pro 9000
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 002: ID 045e:00d1 Microsoft Corp. Optical Mouse with Tilt Wheel
Bus 001 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub


lsusb command reveals a camera type plugged into your system. Output of lsusb command does not necessary means that your camera is now ready to use. Let's see if some modules are associated with video:
$ lsmod | grep video
OUTPUT:
uvcvideo               45800  0
compat_ioctl32          1312  1 uvcvideo
videodev               27520  1 uvcvideo
v4l1_compat            12260  2 uvcvideo,videodev
usbcore               118192  7 snd_usb_audio,snd_usb_lib,uvcvideo,usbhid,ehci_hcd,ohci_hcd


This looks very promising. My camera is using uvcvideo module. If you do not see any ouptut or you see only output not related to your camera device you may need to recompile your kernel or install an appropriate module.

Now we need to find a device file corresponding with your camera. To do that we use xawtv utility:

NOTE: if xawtv command is not avaialable you need to install xawtv package.
$ xawtv -hwscan
OUTPUT:
This is xawtv-3.95.dfsg.1, running on Linux/i686 (2.6.26-2-686)
looking for available devices
port 65-96
type : Xvideo, image scaler
name : NV Video Blitter

/dev/video0: OK                         [ -device /dev/video0 ]
type : v4l2
name : UVC Camera (046d:0990)
flags:  capture


The device file assciated with my camera is /dev/video0 . You may also see an error on your terminal saying: open /dev/video0: Permission denied. To fix this problem you need to make your self a part of a group "video". Now test your camera with a following command:
$ xawtv -c /dev/video0
If you had some issues in some of the previous steps, here are some links, which may assist you to troubleshoot your problem:
To use a camera with the OpenCV library is simple as writing a program to play video. Copy a previously created source code of your video player program and change line:

CvCapture* capture = cvCreatefileCapture(argv[1]);
to:
CvCapture* capture = cvCreateCameraCapture(0);

So the whole code will look similar to the one below:
#include "highgui.h"
int main( int argc, char** argv ) {
cvNamedWindow( "Example2", CV_WINDOW_AUTOSIZE );

CvCapture* capture = cvCreateCameraCapture(0) ;
IplImage* frame;


while(1) {
frame = cvQueryFrame( capture );
if( !frame ) break;

cvShowImage( "Example2", frame );
char c = cvWaitKey(33);
if( c == 27 ) break;

}
cvReleaseCapture( &capture );
cvDestroyWindow( "Example2" );
}
Notice that a function cvCreateCameraCapture() did not take any specific device file or argument. In this case OpenCV will start using the first available camera in your system. Compile and execute this program and if everything up to this point went well you should see yourself on your screen.

NOTE: Return to an image conversion section above, if you need help on how to compile this OpenCV program.

4.5. Write avi file from a camera

The last example will attempt to read an input from a camera and write it to a file. In the meantime, the program will also display a window with a camera input video stream. The Video input is saved to a file supplied as an argument on the command line. The codec used is specified by FOURCC ( Four Character Code ) MJPG which in this case is Motion JPEG. This sample program is very basic and there is a plenty of room for improvement:
#include <cv.h>
#include <highgui.h>
main( int argc, char* argv[] ) {

    CvCapture* capture = NULL;
    capture = cvCreateCameraCapture( 0 );

IplImage *frames = cvQueryFrame(capture);

// get a frame size to be used by writer structure
CvSize size = cvSize (
    (int)cvGetCaptureProperty( capture, CV_CAP_PROP_FRAME_WIDTH),

    (int)cvGetCaptureProperty( capture, CV_CAP_PROP_FRAME_HEIGHT)
);

// declare writer structure
// use FOURCC ( Four Character Code ) MJPG, the motion jpeg codec
// output file is specified by first argument
CvVideoWriter *writer = cvCreateVideoWriter(
    argv[1],

    CV_FOURCC('M','J','P','G'),
    30, // set fps
    size

);
//Create a new window
cvNamedWindow( "Recording ...press ESC to stop !", CV_WINDOW_AUTOSIZE );
// show capture in the window and record to a file
// record until user hits ESC key
while(1) {

 frames = cvQueryFrame( capture );
 if( !frames ) break;
 cvShowImage( "Recording ...press ESC to stop !", frames );
 cvWriteFrame( writer, frames );

 char c = cvWaitKey(33);
   if( c == 27 ) break;
}
cvReleaseVideoWriter( &writer );
cvReleaseCapture ( &capture );
cvDestroyWindow ( "Recording ...press ESC to stop !");

return 0;

}
Assuming that you saved and compiled this programm as "save-camera-input" you can strat recording a video to a video-file.avi with this command:
NOTE: Return to an image conversion section above, if you need help on how to compile this OpenCV program.
$ ./save-camera-input video-file.avi

5. Conclusion

This article should give a you a good start to OpenCV library from an installation perspective. Examples presented do not have much to do with Computer Vision itself, but rather they provide a good testing ground for your OpenCV installation. Even from these simple OpenCV examples it is also clear that OpenCV is a highly civilized library since with just couple lines of OpenCV code you can achieve great results. Your comment on this article is highly appreciated as it may have a great impact on article quality. There is more comming about OpenCV, so stay tuned by subcribing to linuxconfig.org RSS feed ( top left corner ).

Share this linux post:

Bài đăng phổ biến