Wednesday, 21 December 2016

Library program in which Book has multiple authors and Shelf has multiple books using Arrays of structures


Have the following structs, for Book, Author and Shelf. Book has multiple authors and Shelf has multiple books. Write a program to create a functions new_author (), new_book (), print_book (), add_author_to_book (), new_shelf (), delete_shelf (), print_shelf(), add_book_to_shelf() with required return types and parameters.


#include<stdio.h>
#include <stdlib.h>
#define NA 100
#define NB 100
#define NS 100
int ca=0,cb=0,cs=0;
struct author
{
    int aid;
    char name[20];
   
}a[NA];
struct book
{
    char title[25];
    int bid,faid[5],cab;

}b[NB];
struct shelf
{
    int sid,fbid[100],csb;
}s[NS];

void add_author()
{
    a[ca].aid=ca;
    printf("enter the name of author");
    scanf("%s",&a[ca].name);
    ca++;
}
void add_book()
{
    int temp;
    b[cb].bid=cb;
   
    printf("enter the title of the book ");
    scanf("%s",&b[cb].title);
    b[cb].cab=0;
    cb++;
}
void add_author_to_book()
{
    int t1,t2,c1;
    printf("enter the book id and author id");
    scanf("%d%d",&t1,&t2);
    c1=b[t1].cab;
    b[t1].faid[c1]=t2;
    b[t1].cab++;
}
print_author()
{
    int i;
    for(i=0;i<ca;i++)
    {
        printf("\n%d\t%s",a[i].aid,a[i].name);
    }
}
print_book()
{
    int i,j;
    for(i=0;i<cb;i++)
    {
        printf("\n%d\t%s",b[i].bid,b[i].title);
        for(j=0;j<b[i].cab;j++)
        {
            printf("\n author = %s",a[b[i].faid[j]].name);
        }
    }
}
void add_shelf()
{
    s[cs].sid=cs;
    s[cs].csb=0;
    cs++;  
}  
void add_book_to_shelf()
{
    int b1,s1;
    printf("enter shelf id and book id");
    scanf("%d%d",&s1,&b1);
    s[s1].fbid[s[s1].csb]=b1;
    s[s1].csb++;
  
}
void print_shelfid()
{   
    int i;
    for( i = 0 ; i < cs; i++ )
         printf("%d\n", s[i].sid);   
}
void print_books_in_shelf()
{
    int sid1,i;
    printf("enter shelf id");
    scanf("%d",&sid1);
    for(i=0;i<=s[sid1].csb;i++)
    {
        printf("\n%s",b[s[sid1].fbid[i]].title);
    }
}
void delete_shelf()
{
    int sid2,i;
    printf("enter shelf id");
    scanf("%d",&sid2);
    if ( sid2 >cs )
      printf("Deletion not possible.\n");
   else
   {
      for ( i = sid2 - 1 ; i < cs ; i++ )
         s[i] = s[i+1];
       cs--;
    }
}
main()
{
    int choice;
    printf("\n Press 1. add author\n2. print authors \n");
    printf("3. add book\n4. add author to book\n5. print book");
    printf(" 6. add shelf\n7. print shelf \n");
    printf("8. add book to shelf\n9. print books in shelf \n10. delete shelf\n11. exit\n");
    while(1)
    {
      printf("enter ur choice");
      scanf("%d",&choice);
      switch(choice)
      {
          case 1:    add_author();
                  break;
        case 2:    print_author();
                break;
        case 3:    add_book();
                break;
        case 4:    add_author_to_book();
                break;
        case 5: print_book();
                break;
        case 6: add_shelf();
                break;
        case 7: print_shelfid();
                break;
        case 8:    add_book_to_shelf();
                break;
        case 9:    print_books_in_shelf();
                break;
        case 10: delete_shelf();
                break;
        case 11: exit(0);
        default: printf("invalid choice");
    }
    }
}

Circular Array Loop detection C program


You are given an array of positive and negative integers. if a number n at an index is positive, then move forward n steps. Conversely, if its negative, move backwards n steps. Determine if there is a loop in this array. For Example given the array [2,-1,1,2,2] index 0 maps to index 2,1 maps to 0,2 maps to 3 and so on. There is a loop in this array because 0 maps to 2,2 maps to 3,3 maps to 0.(Use the modulo operator)
Solution 1:
#include<stdio.h>
    #include<stdlib.h>
    main()
    {
       
        int a[10],n,i,k,x,c;
        printf("enter the size of array");
        scanf("%d",&n);
        printf("enter the elements");
        for(i=0;i<n;i++)
scanf("%d",&a[i]);
        x=k=0;
        c=0;
        while(c<n) //we can have maximum of n jumps
        {
        //printf("\t%d\t",k);
  if(a[k]==0)
  {
printf("element value cannot be zero");
exit(0);
}
else if(a[k]>0)
            {
 k=(k+a[k])%n;
}
else if(a[k]<0)
            {
            k=(k+a[k])%n;
            if(k<0)
  k=n+k;
            }
            if(x==k)
            {
              printf("loop exists");
                exit(0);
}
            c++;
}
}

(OR)

Below this recursive implementation, you have simple code
#include<stdio.h>
#include<stdlib.h>
void fun(int ,int ,int );
int b[10][10];
main()
    {
       
        int a[10],n,i,k,x;
        printf("enter the size of array");
        scanf("%d",&n);
        printf("enter the elements");
        for(i=0;i<n;i++)
        scanf("%d",&a[i]);
        for(i=0;i<n;i++)
        {
            k=i;
            if(a[k]==0)
                  {
                    printf("element value cannot be zero");
                    exit(0);
                }
                else if(a[k]>0)
                {
                  k=(k+a[k])%n;
                  //printf("\n%d",k);
                }
                  else if(a[k]<0)
                {
                    k=(k+a[k])%n;
                    if(k<0) k=n+k;
                    //printf("\n%d",k);
                }
                b[i][0]=i;
                b[i][1]=k;
              
        }
              
        k=0;
        for(i=0;i<n;i++)
    {
         x=b[i][0];
         fun(i,k,x);
    }
}
void fun(int i,int k,int x)
{
        for(k=k+1; k<5;k++)
        {
                if(b[i][1]==b[k][0])
                {
                        if(x==b[k][1])
                        {
                                printf("loop exists");
                                exit(0);
                        }
                        else
                         fun(k,1,x);
                }
        }
}

(OR)


#include<stdio.h>
#include<stdlib.h>
main()
{

    int a[10],n,i,k,x,j,c,t;
    printf("enter the size of array");
    scanf("%d",&n);
    printf("enter the elements");
    for(i=0;i<n;i++)
    scanf("%d",&a[i]);
    for(i=0;i<n;i++)
    {
        x=i;k=i;
          c=0;
          while(c<n) //Atmost we can have maximum of n jumps
          {
            if(a[k]==0) 
            {
                printf("element value cannot be zero");
                exit(0);
            }
            else if(a[k]>0)
            {
              k=(k+a[k])%n;
            }
            else if(a[k]<0)
            {
                k=(k+a[k])%n; //if k+a[k] is negative then (k+a[k])%n is also negative
                if(k<0) k=n+k;
/* if the index k is negative we have to loop back to last element in the array.
This can be achieved by doing subtracting from n and 
since k is negative, n+k will be do the subtraction from n*/
             }
            if(x==k)
            {
                printf("loop exists");
                exit(0);
            }

            c++;
        }
    }
}

Friday, 9 December 2016

Python 2.7 OpenCV3 tutorial

Reading Images
To read an image as it is
            >>>import cv2
            >>> a=cv2.imread('D:/1.jpg')
                                    (or)
            >>> a=cv2.imread('D:/1.jpg',-1) #the default
                                    (or)
            >>> a=cv2.imread('D:/1.jpg',cv2.IMREAD_UNCHANGED)
To  show an image
            >>> cv2.imshow('window_name',a)
            >>>cv2.waitKey(0)
window_name can be any name u like. cv2.waitKey(milliseconds) returns ASCII value of the key pressed on the Keyboard
To destroy the window created through imshow
To destroy all windows,
            >>>cv2.destroyAllWindows()
To destroy a specific window only,
            >>>cv2.destroyWindow('window_name')
To check the dimensions of the image read
>>> import cv2
>>> image=cv2.imread('1.png')
>>> image.shape
(450, 300, 3)
#450 rows, 300 columns and 3 planes
>>> (rows,columns,channels)=image.shape

Converting an image into gray scale  





To find different flags available in opencv
To find the list of color conversion possible
            >>> flags= [i for i in dir(cv2) if i.startswith('COLOR_')]
            >>> print flags
To find the flags for events in opencv
            events=[i for i in dir(cv2) if 'EVENT' in i]
            print events
To find the different line flags available
            >>> flags= [i for i in dir(cv2) if i.startswith('LINE_')]
            >>> print flags
To find the different FONT flags available
            fonts=[i for i in dir(cv2) if 'FONT' in i]
            print fonts

To draw a Line 



To draw a rectangle 


 To Draw an Ellipse

                                                                               
To add text to images 



 To resize an image

  
To copy an image
image=cv2.imread(‘C:/1.jpg’)
copied=image.copy()

Convert image to binary image, based on threshold
>>> gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
>>> ret1,thresh1=cv2.threshold(gray,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
>>> ret1
149.0 # threshold value decided by OTSU and all the pixels intensity above this threshold is made 255
#thresh1 is the binary image.
>>> ret,thresh=cv2.threshold(gray,50,255,cv2.THRESH_BINARY)
>>> ret
50.0# threshold value decided by u i.e, second argument
To find contours
_,contours,hierarchy=cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)


To flip an image
rimg=cv2.flip(img,1) #vertical flip
fimg=cv2.flip(img,0) #horizontal flip
Image Arithmetic

Adding two images

added=cv2.add(img1,img2)

added=cv2.addWeighted(img1,0.7,img2,0.3,0)

Absolute difference of two images

difference= cv2.absdiff(img1,img2) 
                                                                               
Creating the negative of an binary image

binaryInvert=cv2.bitwise_not(binary_imag)

 Find the edges of an image using Canny
edges = cv2.Canny(image,100,200)

Gradient Filters

1. sobelx=cv2.Sobel(image,cv2.CU_64F,1,0,5)
   sobely=cv2.Sobel(image,cv2.CU_64F,0,1,5)

2. lap=cv2.Laplacian(image,cv2.CU_64F,0,1,5)

























Sunday, 23 October 2016

Creating GUI using guide in MATLAB to retreive images in a folder and display

function varargout = untitled(varargin)
% UNTITLED MATLAB code for untitled.fig
%      UNTITLED, by itself, creates a new UNTITLED or raises the existing
%      singleton*.
%
%      H = UNTITLED returns the handle to a new UNTITLED or the handle to
%      the existing singleton*.
%
%      UNTITLED('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in UNTITLED.M with the given input arguments.
%
%      UNTITLED('Property','Value',...) creates a new UNTITLED or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before untitled_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to untitled_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help untitled

% Last Modified by GUIDE v2.5 13-Dec-2015 00:03:51

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @untitled_OpeningFcn, ...
                   'gui_OutputFcn',  @untitled_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before untitled is made visible.
function untitled_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to untitled (see VARARGIN)

% Choose default command line output for untitled
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes untitled wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = untitled_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;



function edit1_Callback(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit1 as text
%        str2double(get(hObject,'String')) returns contents of edit1 as a double


% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

first=get(handles.edit1,'string');
foldername=strcat('C:\',first,'\'); #PATH TO FOLDER IS IN RED COLOUR
imname=strcat(foldername,'\*.png');
n = length(imname);   
imgs=dir(imname);
filename=strcat(foldername,'\',imgs(1).name);
Cval = imread(filename);
handles.C = Cval;
axes(handles.axes1);
imshow(Cval);
handles.output = hObject;
guidata(hObject, handles);

filename2=strcat(foldername,'\',imgs(2).name);
Cval = imread(filename2);
handles.C = Cval;
axes(handles.axes2);
imshow(Cval);
handles.output = hObject;
guidata(hObject, handles);


All the code above in green colour is automatically generated by guide in MATLAB
U have to create a figure using guide in matlab and give it the name untitled.fig as the code has the name untitled.
Also you have to create a folder named actress i.e, same as the name of the folder u type in the search box in the below figure.


Output:

Monday, 17 October 2016

Preprocessing satellite images to find crowns of trees using MATLAB

MATLAB Program: 
clear all;
close all;
g=imread('test_area_1.tif');
l=[100/255 75/255 50/255];
h=[255/255 255/255 250/255];
b=imadjust(g,[l;h],[0;1]);
H = padarray(2,[2 2]) - fspecial('gaussian' ,[5 5],2); % create unsharp mask
d=imfilter(b,H);
subplot(131);imshow(g);title('
original');
subplot(132);imshow(b);title('Contrast stretched image');
subplot(133);imshow(d);title('sharpened image');


By contrast stretching the image using imadjust and by applying high pass filter for sharpening, the results are as shown below:








 

Friday, 29 April 2016

Histogram of Oriented Gradients (HoG)

1) First apply Gaussian Smoothing Mask on the image.
2) The given image is divided into 16x16 blocks each of 2x2 cell and each cell is 8x8.  Block1 is as shown in the above figure WITH 50% Overlap



If the image is of size 64x128, we get 105 blocks.

3) Compute gradient magnitude and gradient direction for each block.

4) We look at gradient direction and quantize orientation into any of  9 bins (0- 180 degrees) as shown below












5) If direction is not in one of the bins we use interpolation.
6) Concatenate all descriptors i.e, 105 blocks each of 9 dimensions as we have 9 bins.  Hence we get a total of 3780 descriptors .(each block is further divided into 2x2 cells each of size 8 so 2*2 =4 and for each 8x8 , 9 bins and hence 4*9*105=3780)
7)We plot histogram
x-axis of histogram is the bin values say (20 degrees, 40 degrees...as shown in the above figure).
y-axis is the count. We count how strong the gradient direction is using gradient magnitude( vote).

To Learn more about HoG watch the video at the link given below https://www.youtube.com/watch?v=0Zib1YEE4LU
To learn more about descriptors like SIFT etc.. follow the below link
https://gilscvblog.com/2013/08/26/tutorial-on-binary-descriptors-part-1/
https://www.youtube.com/watch?v=4ESLTAd3IOM