OpenCV+Python:Part 2–Working with Images

–Access and Edit Pixel Values

All of the following steps can be performed using the Python terminal.
First of all load the image:

>>>import cv2
>>>import numpy as np
>>>img = cv2.imread('image.jpg')

To get a pixel value of a particular position:

>>>pix = img[x,y] #x,y are the coordinates
>>>print pix

To modify the pixel value of a particular point (x,y)

>>>img[x,y]=[B,G,R] #where B,G,R are integer values

A much faster method is using Numpy functions array.item() and array.itemset() to access and edit pixel values.However it only returns a scalar value.So to access the B,G,R values you need call the function array.item() separately for all.

–Image Properties
1.)>>>print image.shape
Its returns the a tuple with number of rows,columns and channels.
2.)>>>print image.size
Returns the numbers of pixels accessed by the image.
3.)>>>print img.dtype
Returns the Image datatype.

–ROI
To select a particular region of image:
>>>part = img[x1:y1,x2:y2]

To paste the selected ROI at some other location:
>>>img[p1:q1,p2:q2] = part

–Splitting and Merging Channels

If you want to split B,G,R channels or merge them back use:

>>>b,g,r = cv2.split(img)
>>>img = cv2.merge(b,g,r)

However if you want to edit a particular channel a faster method would be to use numpy.
E.g. to set all red pixels to zero:

>>> img[:,:,2] = 0

Thats all in this post..

Advertisements

OpenCV+Python Part 1–Working with Videos

Learn how to load, display and save videos. I’ll explain this using the code snippets.The following program captures a video from the camera (I am using the in-built webcam of my laptop) and displays it.

import numpy as np
import cv2

x = cv2.VideoCapture(0)

while(True):
# Capture frame-by-frame
ret, frame = x.read()

# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break

# When everything done, release the capture
x.release()
cv2.destroyAllWindows()

The first thing that we need to do is to create a Video Capture object ‘x’.The argument passed to it is either the Device Index(a number to specify which camera) or the name of a video file. Normally since only one camera is connected to the system a 0 is passed. To select a second camera you can pass a 1 and so on.

cap.read() checks if the frame is read correctly and returns a boolean value.

Next lets play a video from a file.

First of all–
Go to : OpenCV\3rdparty\ffmpeg\
Copy the dll files opencv_ffmpeg.dll or opencv_ffmpeg_64.dll (depending on your system architecture) and paste them into C:\Python27\

Now rename both these to opencv_ffmpeg24x.dll or opencv_ffmpeg24x_64.dll where x is the version of opencv you are using. For example I am using OpenCV 2.4.6 so I renamed them
opencv_ffmpeg246.dll or opencv_ffmpeg246_64.dll.

Then using the following code snippet you can play any video from the current directory.

import numpy as np
import cv2

cap = cv2.VideoCapture('video.mp4')

while(cap.isOpened()):
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break

cap.release()
cv2.destroyAllWindows()

Now the final step is to save a video from a cam.
The code captures from a Camera, flips every frame vertically and saves the video.

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object
fourcc = cv2.cv.CV_FOURCC(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))

while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
frame = cv2.flip(frame,0)

# write the flipped frame
out.write(frame)

cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break

# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()


For images we can easily used the function cv2.imwrite().However with videos it gets a bit tough.
Now along with a VideoCapture object we create a VideoWriter object where the arguments are the following:
1.)The name of the output file.
2.)Then we specify the FourCC code.FourCC is a 4-byte code used to specify the video codec.
Download the codec file for windows from — FourCC Codec.
3.)The number of frames per second(fps).
4.)The frame size.

That is all in this post..! All the best.

Matlplotlib+OpenCV

Matplotlib is a plotting library for Python which gives you wide variety of plotting methods.You can zoom images, save it etc using Matplotlib.
First of all to use matplotlib you need to have certain other libraries too:
1.)Numpy
2.)Dateutil
3.)Pytz
4.)Pyparsing
5.)Six

All of these can be found at — LINK

After setting up everything you will now be able to peacefully use matplotlib.

Here is an example code:

import numpy as np
import cv2
from matplotlib import pyplot as plt

img = cv2.imread('image.jpg',0)
plt.imshow(img, cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis
plt.show()

For further info on matplotlib visit — LINK

OpenCV+Python:Part1–Working with Images

This post is about opening,displaying and saving images.

cv2.imread()

This function is used to read an image. Either the image is in the current working directory or the full path is provided as an argument.

The second argument specifies the way the image is read.

1.)cv2.IMREAD_COLOR : x = cv2.imread('image.jpg',1)— Loads a color image. Any transparency of image will be neglected. It is the default flag.

2.)cv2.IMREAD_GRAYSCALE : x = cv2.imread('image.jpg',0)— Loads image in gray-scale mode.
3.)cv2.IMREAD_UNCHANGED : x = cv2.imread('image.jpg',-1)— Loads image as such including alpha channel.

The full code to load an image would look something like this:

import numpy as np
import cv2
x = cv2.imread('image.jpg',1)


————————————————————————————————————

cv2.imshow()

This function is used to display an image in a window.The window automatically fits the image size.
There are two arguments again.The first argument provides a name to the window given as a string. The second argument provides the variable in which the image is stored.

cv2.imshow('window_name',x)

The full code to create a window that stays until an exit key is pressed is as follows:

cv2.imshow('window_name',x)
cv2.waitKey(0)
cv2.destroyAllWindows()

cv2.waitKey(0) takes arguments as milliseconds. Passing 0 makes the function wait until any key is pressed. For 64-bit machine the code has to of this form : cv2.waitKey(0) & 0xFF

cv2.destroyAllWindows() does as the name suggests.

————————————————————————————————————-

cv2.imwrite()

This function is used to save the image after processing.It takes in two arguments. First is the name of the file to written. Second is the variable in which the image is saved.

cv2.imwrite('image.png',x)

————————————————————————————————————–

The whole post can be summarized by the following code. It loads an image from the current working directory and saves it as a png black n white image.

import numpy as np
import cv2
x = cv2.imread('image.jpg',0) #load a jpg image
cv2.imshow('image',x) #display image
cv2.waitKey(0) & 0xFF #wait for key press
cv2.imwrite('image.png',x) #save the image as png
cv2.destroyAllWindows() #destroy all windows

Thats all !!

Open-CV+Python

Assuming you know a bit of Python(and if you don’t take a crash course at Codecademy or Learn Python the Hard Way) the next few posts will be about how to work on Open-CV with Python.
You also need to know a bit of numpy for this so if you are not familiar with this visit :Numpy Tutorials
The following steps are for Windows.

So first of all lets set up your machine:
Download the following and install:

1.)Python-2.7
2.)Numpy
3.)Matplotlib
4.)DownloadOpenCV-2.4.x and extract.

After installing the above go to opencv/build/python/2.7
Copy cv2.pyd to C:/Python27/lib/site-packages

To test the installations:
1.) Open IDLE and type import numpy. If this returns no error then numpy has been installed correctly.
2.) Now type import cv2 and print cv2.__version__

If the results are printed without any errors the installation has been successful

ODROID-X2 with Arch Linux ARM

Odroid-X2 is a powerful Linux computer with an Exynos 4412 ARM Cortex-A9 Quad Core CPU and 2GB of RAM. It has 6 USB 2.0 ports, micro HDMI, Wifi and Bluetooth adapters, 1.8v serial adapter and an eMMC storage module.

To run the Odroid in headless mode in case you do not have a HDMI display follow this procedure:

For Windows Users:
1.) Buy a 8GB or larger SD card(preferably class 10).
2.) Download the ODROID-X2 SD image
3.) Download Image Writer for Windows and write the Odroid X2 image file into the SD card
4.) Insert the SD card into the odroid and power up the board. Connect it to your local router.
5.) Download Zenmap and scan your local host address (generally its 192.168.0.*) to find out the IP assigned to the odroid.
6.) Download Putty and connect to the odroid via SSH.

That’s all !

Setting up a Headless Raspberry Pi:Part 3

Now that you have found the IP address of the raspberry pi we can proceed further. We can log into the pi using ssh,the secure shell.
ssh [options] username@remote computer

By default the raspberry Pi has a username “pi” and the password “raspberry”(without quotes).
The complete command looks like:
ssh pi@192.168.0.101

As this is the first time the pi has been connected to, ssh will tell you that, “The authenticity of host [host name] can’t be established”. You don’t need to worry about this.Just proceed by typing yes.

First of all this is a text interface so mouse cannot be used. You move between the different items with the arrow keys and select them by hitting enter. If you need to select a check box on one of the later screens, you hit space, and when you’re done, you move between the list of actions and the buttons at the bottom by pressing the “tab” key.

Have FUN!!

Setting up a Headless Raspberry Pi:Part 2

So, now you have connected your pi to either your router, network or computer. Plug in the power supply and turn it on. You now have a working Raspberry Pi (HEADLESS!!) Let’s configure it. The first thing that we need to do is find the IP address of the raspberry pi.
Depending on how you connected the pi to your network , 3 cases may arise.
1.) Pi connected to computer :
You need to check the log of the computer to find the address assigned to the raspberry pi.In your terminal type:
tail /var/log/syslog

This command shows the last 10 lines of the log file.Look for a line which says dnsmasq-dhcp.If you don’t find it try typing :
grep dnsmasq-dhcp /var/log/syslog
This will search for dnsmasq-dhcp in the system log and return the results.The most recent connection made would be the raspberry pi.The IP address followed by the mac address of the raspberry pi will be printed.
2.)Pi connected to router :
This is simple.Just log into your router’s system setting and look for the routing table where the router registers the IP and mac addresses of the connections it has made.
3.)Pi attached to a network :
Install zenmap:
sudo apt-get install zenmap
Run zenmap as root:
sudo zenmap
Find out your IP range. We are interested in the interface that is connected to the same network as the pi. For example since I connected my raspberry to the router and my router has a netmask of 255.255.255.0, and my system IP is 192.168.0.100, so the router will give out IP address in the range 192.168.0.0-192.168.0.255.
For this case enter 192.168.0.* in the target box of zenmap and let it scan. The zenmap will scan the network and return the IP address alongside the mac address of the pi.

Setting up a Headless Raspberry Pi:Part 1

So you have bought a raspberry pi but missed to buy a screen for it and are clueless right now as to what are you going to do. This post is for you.
I am working on Ubuntu ,however the steps will be very much similar for any other operating system. I assume you do have an internet connection and a spare network socket(either in your system or you have a router).
Stuff required:
1.) A raspberry pi(Model B)
2.) Power adapter for raspberry pi
3.) An SD card(min 4GB)
4.) An ethernet cable(to connect the pi to internet)

Alright then, first you need to set up the operating system for the raspberry pi.
For general usage Raspbian is the most comfortable OS. Of the different distributions, there are a few different images you can get, which have different default setups, but don’t worry about them for now. Just go get the default Raspbian Image from Raspbian

Now, there are some nice easy graphical programs for writing images to disk. If you want to take this route, install usb-creator-gtk and write the raspbian image onto the SD card.
Now you can stick the SD card in the pi and power it up.
However to use it you need to connect it to a network.

If you need to setup a shared connection to your pi, click on the networking icon in the top right hand of your screen and select “Edit Connections” . In the dialog box that pops up, making sure you are on the “Wired” tab, click “Add”. Give the connection a name, click on the “IPv4 Settings” tab and select “Shared to other computers” (all the other fields can be left as they are, though if you aren’t going to be leaving the pi connected to the computer in this manner permanently, you might want to uncheck “Connect Automatically”). Then click ok.

Now click the networking icon again in the top right hand corner, and select the connection you just created (you might first have to disconnect a wired connection if one is set to connect automatically). This will set up a small network consisting of your computer and the pi that is connected to your main internet connection.

MASM in Ubuntu

In this post I explain how to use MASM assembler with Ubuntu(Linux):
Installing Dosbox
Fire up the terminal and type:
sudo apt-get update
sudo apt-get install dosbox

For non-ubuntu users
Download Dosbox from here:Dosbox
Now install the tar file:
tar -xzvf dosbox-0.74.tar.gz
cd dosbox-0.74
./configure
make

Now download MASM assembler from here:
MASM
Extract the zip file in your home directory.
Now run dosbox and type:
mount c /home/username/8086
C:

In place of username type your in your computers name.
This will mount the MASM directory
And you are ready to do your labwork..!!