Thursday, August 29, 2013

Noise removal from foreground and background area in an image using opencv (python)



import cv2
import numpy as np

# To display a single image in a window
# Window is destroyed on pressing any key
def display(windowName, image):
  cv2.namedWindow(windowName, 1)
  showtime(windowName, image)
  cv2.waitKey(0)
  cv2.destroyAllWindows()

# Read image
img = cv2.imread('imagename.jpg')
# Convert to grayscale image
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
display('gray', gray)
# Convert to binary image
ret,thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
display('binary', thresh)

# noise removal
# to remove any small white noises use morphological opening
kernel = np.ones((3,3),np.uint8)
opening = cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel, iterations = 2)
sure_bg = cv2.dilate(opening,kernel,iterations=3)
display('Sure Background', sure_bg)

dist_transform = cv2.distanceTransform(opening,cv.CV_DIST_L2,5)
ret, sure_fg = cv2.threshold(dist_transform,0.7*dist_transform.max(),255,0)
display('Sure Foreground', sure_fg)

# Finding unknown region
unknown = cv2.subtract(sure_bg,sure_fg)
display('unknown area', unknown)


For knowing more on morphological transformations using opening and closing refer Morphological Transformation

Written by

Wednesday, June 19, 2013

Interview Question (Programming in C++)

Give the output of the following program :

class Animal
{
  public :
  virtual void draw()
  {
    cout<<”Animal”;
  }
};
class Leopard : public Animal
{
  public :
  virtual void draw()
  {
    cout<<”Leopard”;
  }
};
main()
{
  Leopard l;
  Animal *a=&l;
  l.draw();
}

(A) Leopard (B) Animal (C) LeopardAnimal (D) AnimalLeopard

Answer :
(A) Leopard

Explanation :
The virtual keyword  indicates to the compiler that it should choose the appropriate definition of the function draw not by the type of reference, but by the type of object that the reference refers to.
For more details on the use of virtual keyword : Reference

Written by

Interview Question (Programming)

What does the following function check?

bool f(unsigned int v)
{
  return ((v!=0)&&!(v & v-1));
}

(A) v is an odd number (B) v is a multiple of 2 (C) v is a power of 2 (D) v has a 0 bit

Answer :
(C) v is a power of 2

Explanation :
1) If v is a power of 2,

  • v is never 0 (even 2^0 = 1) and (v != 0) will always be 1(True).
  • (v & v-1) will always be 0(False) and hence their negation will always be 1(True).
2) If v is not a power of 2, either
  • v = 0, or
  • (v & v-1) is something other than 0 and their negation is 0(False)


Written by

Wednesday, June 5, 2013

Cut the Gold Bar Twice and Pay for 7 Days - Puzzle#1

Puzzle : You have a 7 inch gold bar with you. You need to pay the servant 1 inch gold per day of work. (At the end of first day, servant should have 1 inch gold; at the end of second day, he should have 2 inch gold and so on). You may take back some of the given pieces if needed. How will you do this with minimum number of cuts of the gold bar?

Answer : 2 cuts (i.e 3 pieces => a 4 inch piece, a 2 inch piece and a 1 inch piece)

Explanation : TB = Take back



Written by

Saturday, June 1, 2013

Convolution of Two Images (matrix form) - OpenCV - Python

To perform convolution of two matrices


import cv2.cv as cv
import sys

if __name__ == '__main__':
  mat1 = cv.CreateMat(3, 3, 8)
  mat2 = cv.CreateMat(3, 3, 8)
  dst = cv.CreateImage(cv.GetSize(mat1), 8, 3)

  kernel = [[0, 0, 0], [0, 1, 0], [0, 0, 0]]
  matrix2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
  for i in range(3):
    for j in range(3):
      mat1[i][j] = kernel[i][j]
  for i in range(3):
    for j in range(3):
      mat2[i][j] = matrix2[i][j]

  cv.NamedWindow("convolution", 1)
  cv.Filter2D(mat2, dst, mat1)
  cv.ShowImage('convolution', dst)

  print 'Press any key to quit'
  cv.WaitKey(0)
  print 'Exiting...'
  cv.DestroyAllWindows()
  sys.exit(0)


Written by

Convolution of Two Images - OpenCV - Python

# To convolute two images img1.bmp and img2.bmp

In mathematics and, in particular, functional analysis, convolution is a m-
athematical operation on two functions f and g, producing a third function
that is typically viewed as a modified version of one of the original func-
tions, giving the area overlap between the two functions as a function of 
the amount that one of the original functions is translated.
-Wikipedia


import cv2.cv as cv
import sys

if __name__ == "__main__":
 # Load two images
 im1 = cv.LoadImageM("img1.bmp")
 im2 = cv.LoadImageM("img2.bmp")
 # Create a destination image of the same size that of the source
 dst = cv.CreateImage(cv.GetSize(im1), 8, 3)

 # Create a window named "convolution(1 for colour)"
 cv.NamedWindow("convolution", 1)
 # Convolute the 2 images
 cv.Filter2D(im1, dst, im2)
 # Show the convoluted result
 cv.ShowImage('convolution', dst)

 # Wait for any key press to close the window
 print 'Press any key to quit'
 cv.WaitKey(0)
 # Destroy all created windows and exit
 print 'Exiting...'
 cv.DestroyAllWindows()
 sys.exit(0)


Written by

Friday, March 29, 2013

GATE 2013 - Papers, Answer Keys and Solutions

GATE 2013 Question papers and the corresponding answer keys are now available for download. These are the official questions papers and answer keys provided by IITB. They are also available from IITB GATE 2013 website.

Computer Science & Information Technology


Written by
Information courtesy: IITB GATE 2013 Website

GATE 2013 - CS/IT Question Papers, Answer Keys and Solutions

GATE 2013 Computer Science and Information Technology Question Papers are available under 4 paper codes; A, B, C & D. All of them have the same questions (both in number and content) but presented in different order. You can view the questions papers here or download for offline use by clicking the corresponding "Download" button.

Monday, January 7, 2013

Bellman-Ford Algorithm - Shortest Path Algorithm

"The Bellman–Ford algorithm computes single-source shortest paths in a weighted digraph.For graphs with only non-negative edge weights, the faster Dijkstra's algorithm also solves the problem. Thus, Bellman–Ford is used primarily for graphs with negative edge weights. The algorithm is named after its developers, Richard Bellman and Lester Ford, Jr. 

Negative edge weights are found in various applications of graphs, hence the usefulness of this algorithm. However, if a graph contains a "negative cycle", i.e., a cycle whose edges sum to a negative value, then walks of arbitrarily low weight can be constructed by repeatedly following the cycle, so there may not be a shortest path. In such a case, the Bellman-Ford algorithm can detect negative cycles and report their existence, but it cannot produce a correct "shortest path" answer if a negative cycle is reachable from the source." - Wikipedia

INITIALISE_SINGLE_SOURCE(G, start)
{
  for each vertex v ∈ v(G)
    dist[v] <- ∞
    pred[v] <- NIL
  dist[start] <- 0
}
// dist[v] <- distance of vertex "v" from vertex "start"
// pred[v] <- predecessor of "v" in the shortest path 
//            from "start"

RELAX(u, v, cost)
{
  if dist[v] > dist[u] + cost[u, v]
    dist[v] <- dist[u] + cost[u, v]
    pred[v] <- u
} 

BELLMAN_FORD(G, cost, start)
{
  INITIALISE_SINGLE_SOURCE(G, start)
  for i <- 1 to |v(G)| - 1
    do for each edge (u, v) ∈ E[G]
      do RELAX(u, v, cost)
  for each edge (u, v) ∈ E[G]
    do if dist[v] > dist[u] + cost[u, v]
      then return FALSE
  return TRUE
}


Written by
Image courtesy - ArsRout

Saturday, January 5, 2013

Dijkstra's Algorithm - Shortest Path Algorithm

"Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path problem for a graph with non negative edge path costs, producing a shortest path tree.

For a given source vertex (node) in the graph, the algorithm finds the path with lowest cost (i.e. the shortest path) between that vertex and every other vertex. It can also be used for finding costs of shortest paths from a single vertex to a single destination vertex by stopping the algorithm once the shortest path to the destination vertex has been determined." - Wikipedia

INITIALISE_SINGLE_SOURCE(G, start)
{
  for each vertex v ∈ v(G)
    dist[v] <- ∞
    pred[v] <- NIL
  dist[start] <- 0
}
// dist[v] <- distance of vertex "v" from vertex "start"
// pred[v] <- predecessor of "v" in the shortest path 
//            from "start"

RELAX(u, v, cost)
{
  if dist[v] > dist[u] + cost[u, v]
    dist[v] <- dist[u] + cost[u, v]
    pred[v] <- u
} 

DIJKSTRA(G, cost, start)
{
  INITIALISE_SINGLE_SOURCE(G, start)
  S <- φ
  Q <- V[G]
  while Q ≠ φ do
    u <- EXTRACT_MIN(Q)
    S <- S U {u}
    for each vertex v ∈ Adj[u]
      do RELAX(u, v, cost)
}
// S <- Set of vertices whose final shortest path weights
//      from the source (start) have already been determined
// Q <- min_priority queue of vertices, keyed by their 'dist'
//      values



Written by