Showing posts with label ImageProcessing. Show all posts
Showing posts with label ImageProcessing. Show all posts

Thursday, 22 August 2019

Resize an image keeping Aspect Ratio using Python

import cv2
import numpy as np

img = cv2.imread('flower.jpg');
# To resize the image keeping aspect ratio
rows=100.0/img.shape[1] #img.shape[1] gives the number of rows
dimensions = (100, int(img.shape[0]*rows))
resized = cv2.resize(img, dimensions, interpolation = cv2.INTER_AREA)
cv2.imshow("Original", img)
cv2.imshow("Resized", resized)
cv2.waitKey(0)
cv2.destroyAllWindows


Output:





















Resized Image:


Monday, 1 April 2019

Loop through images in python using opencv and python3

Below program resizes and converts the images into gray scale and saves the gray images in the same folder where the python program is saved

import os
import cv2
count=0
for filename in os.listdir("./"):
    if filename.endswith(".jpg"):
      count=count+1
      frame = cv2.imread(filename)
      frame = cv2.resize(frame,(60,60))
      gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
      filename=filename.replace('.jpg','')
      filename=filename+"GRAY"
      cv2.imwrite("%s.jpg" % filename ,gray)   
     
    else:
        continue

NOTE the images must be in the same folder where this python program is saved

Resized and gray scale image




Upload a folder that contains images and extract and loop through all the images extracted
import os
import cv2
from zipfile import ZipFile

filename="unpleasantimages.zip"
with ZipFile(filename,'r') as zip:
  zip.extractall()
count=0

for filename in os.listdir("./"):
    if filename.endswith(".jpg"):
      count=count+1
      frame = cv2.imread(filename)
      frame = cv2.resize(frame,(60,60))
      gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
      filename=filename.replace('.jpg','')
      filename=filename+"GRAY"
      print(filename)
      #cv2.imwrite("%s.jpg" % filename ,gray)   
     
    else:
        continue


to remove the folder  in google colab
!rm -rf foldername


filename="images.zip"
with ZipFile(filename,'r') as zip:
  zip.extractall()
count=0

for filename in os.listdir("./images/unpleasant/"):
    if filename.endswith(".jpg") or filename.endswith(".jpeg"):
      count=count+1
      frame = cv2.imread(filename)
      #frame = cv2.resize(frame,(60,60))
      #gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
      filename=filename.replace('.jpg','')
      filename=filename+"GRAY"
      print(filename)
      #cv2.imwrite("%s.jpg" % filename ,gray)   
     
    else:
        continue
for filename in os.listdir("./images/pleasant/"):
    if filename.endswith(".jpg") or filename.endswith(".jpeg"):
      count=count+1
      frame = cv2.imread(filename)
      #frame = cv2.resize(frame,(60,60))
      #gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
      filename=filename.replace('.jpg','')
      filename=filename+"GRAY"
      print(filename)
      #cv2.imwrite("%s.jpg" % filename ,gray)   
     
    else:
        continue

Classification using python3, sklearn with simple example

from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn import svm
from sklearn.metrics import accuracy_score,confusion_matrix

features=[[1.2,1.3],[1.15,1.25],[1.02,1.23],[1.12,1.13]]
labels=[1,1,0,0]
train,test,train_labels,test_labels=train_test_split(features,labels,test_size=0.33)
#gnb=GaussianNB()
gnb = svm.SVC(gamma=0.001)
model=gnb.fit(train,train_labels)
predictions=gnb.predict(test)
print(confusion_matrix(test_labels,predictions))
print(accuracy_score(test_labels,predictions))
# refer https://scikit-learn.org/stable/modules/svm.html
#here i used svm classifier, if u use a DecisionTreeClassifier() and plot the decision tree
#follow the video https://www.youtube.com/watch?v=yU87snVC_Go
from sklearn import tree
from io import StringIO
from IPython.display import Image
with open("classifier.txt","w") as f:
f= tree.export_graphviz(classifier, out_file=f)

# A text file by name classifier will be saved to your current working directory
#Copy the contents of the file and go webgraphviz.com and paste it and click on
#Generate Graph button


Sunday, 17 March 2019

Python code to Read the data in first column in excel file (Text to speech using pyttsx )

import pyttsx
import openpyxl
import time


filename=str(raw_input('enter path to excel file: ')) # enter the complete path of excel file
wb = openpyxl.load_workbook(filename)
ws = wb.get_sheet_by_name('Sheet1') # gets Sheet1 in excel
rowcount=ws.max_row

def say(s):
       engine = pyttsx.init()
       engine.setProperty('volume', 0.2)
       engine.setProperty('rate', 100)
       voices= engine.getProperty('voices')                                                               
       engine.setProperty('voice', 'english-us')                 
       engine.say(s)
       a = engine.runAndWait()

if __name__== "__main__":
       for i in range(rowcount):              # loop through entire rows in excel
               mytext = str(ws.cell(row=i+1,column=1).value) # gets the first column data
               say(mytext)


Usage:
Create an excel file and write any text in the first column as shown below and save it. In this example, i have saved the file in Desktop with the name SEC8


Once u run the python code, you will be asked to
Enter the path where the excel file is
here i have saved the excel file at C:\Users\SARVANI\Desktop\SEC8.xlsx
The excel file name is SEC8.xlsx




Saturday, 14 April 2018

Python code to read words in first column of excel sheet and convert all the words into individual audio files

import tts.sapi
import os
import openpyxl
import time

filename=str(raw_input('enter path to excel file: ')) # enter the complete path of excel file
wb = openpyxl.load_workbook(filename)
ws = wb.get_sheet_by_name('Sheet1') # gets Sheet1 in excel
rowcount=ws.max_row

def say(s):
    voice = tts.sapi.Sapi()
    voice.set_voice("Zira")#u can use the voice of David also
    #you set the rate to say slowly as shown below
    #voice.set_rate(-5)
    filename=str(ws.cell(row=i+1,column=1).value)+'.wav'
    voice.create_recording(filename, s)




if __name__== "__main__":

       for i in range(rowcount):              # loop through entire rows in excel

               mytext = str(ws.cell(row=i+1,column=1).value) # gets the first column data

               say(mytext)

Sunday, 19 November 2017

python code to send SMS data in excel automatically through way2sms

The below code is modification of code found at URL
https://github.com/PratikBodawala/way2sms

 Requirements:
 requests==2.12.4
beautifulsoup4==4.5.3
python 2.7.13

You can also download the code from
https://drive.google.com/file/d/1b-gySD2S5tlyhuwX0LnkyfzEFNMsD_9J/view?usp=sharing

Usage:
Create excel file with msgs in A1,A2,A3 ...cells 
and corresponding phone number in B1,B2,B3 ...cells as shown in below figure



Output:

Once u run the python code
you will be asked to
Enter the way2sms account username i.e, mobile number
Enter the way2sms password
Enter the path where the excel file is
here i have saved the excel file at C:\Users\SARVANI\Desktop\SEC8.xlsx
The excel file name is SEC8.xlsx




===============================================
import getpass
import urllib
import textwrap
import requests
import time
import os
import datetime
from bs4 import BeautifulSoup
import cPickle as pickle
import sys
import openpyxl
sys.stdout.flush()
url = 'http://www.way2sms.com'

class Way2sms(object):
    """mobile and string are keywords parameter of sms method."""
    def __init__(self):
        if os.path.exists('.token'):
            with open('.token', 'r') as Token:
                self.ses, self.token, self.new_url = pickle.load(Token)
            page = self.ses.get(self.new_url+'ebrdg?id='+self.token).text
            if 'Welcome to Way2SMS' in page:
                print 'session is ok'

            else:
                print 'session expired'
                response = requests.head(url, allow_redirects=True)
                self.new_url = response.url
                self.ses = requests.session()
                self.ses.headers.update({'Connection': 'keep-alive', 'Pragma': 'no-cache', 'Cache-Control': 'no-cache', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36', 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'DNT': '1', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'en-US,en;q=0.8'})
                usr = str(raw_input('Enter your mobile number:'))
                pas = getpass.getpass()
                if self.ses.post(self.new_url + 'Login1.action', 'username=' + str(usr) + '&password=' + str(pas)).ok:
                    print "Login successfully"
                    self.token = self.ses.cookies['JSESSIONID']
                    self.token = self.token[4:]
                    with open('.token', 'w') as Token:
                        pickle.dump((self.ses, self.token, self.new_url), Token)
                else:
                    print "Login failed"

        else:
            response = requests.head(url, allow_redirects=True)
            self.new_url = response.url
            self.ses = requests.session()
            self.ses.headers.update({'Connection': 'keep-alive', 'Pragma': 'no-cache', 'Cache-Control': 'no-cache',
                                     'Upgrade-Insecure-Requests': '1',
                                     'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36',
                                     'Content-Type': 'application/x-www-form-urlencoded',
                                     'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                                     'DNT': '1', 'Accept-Encoding': 'gzip, deflate',
                                     'Accept-Language': 'en-US,en;q=0.8'})
            usr = str(raw_input('Enter your mobile number:'))
            pas = getpass.getpass()
            if self.ses.post(self.new_url + 'Login1.action', 'username=' + str(usr) + '&password=' + str(pas)).ok:
                print "Login successfully"
                self.token = self.ses.cookies['JSESSIONID']
                self.token = self.token[4:]
                with open('.token', 'w') as Token:
                    pickle.dump((self.ses, self.token, self.new_url), Token)
            else:
                print "Login failed"
    def successfully_sent(self, mobile, text):
        date = datetime.date.today().strftime('%d/%m/%Y')
        page = self.ses.post(self.new_url + 'sentSMS.action?dt=' + str(date) + '&Token=' + str(self.token))
        soup = BeautifulSoup(page.text, 'html.parser')
        first = soup.find('div', {'class': 'mess'})
        no = str(first.find('b').text)
        divrb = first.find('div', {'class': 'rb'})
        p = str(divrb.find('p').text)
        if (no == mobile) and (p == text):
            return True
        else:
            return False

    def sms(self):
        filename=str(raw_input('enter path to excel file: '))
        wb = openpyxl.load_workbook(filename)
        ws = wb.get_sheet_by_name('Sheet1')
        #print sheet['B1'].value
        rowcount=ws.max_row
        print rowcount
        for i in range(rowcount):
            mobile = str(ws.cell(row=i+1,column=2).value)
            string = str(ws.cell(row=i+1,column=1).value)       
            if type(mobile) is str:
                mobile = list(str(mobile).split(','))
            if type(mobile) is list:
                for mobile_no in mobile:
                    if len(mobile_no) is not 10:
                        print mobile_no, 'is not valid'
                    else:
                        lofstr = textwrap.wrap(string, 140)
                        for string in lofstr:
                            msglen = len(string)
                            qstring = urllib.quote(string)
                            page = self.ses.post(self.new_url+'smstoss.action', 'ssaction=ss&Token='+str(self.token)+'&mobile='+str(mobile_no)+'&message='+qstring+'&msgLen='+str(140-msglen)).text
                            print 'Sending SMS to', mobile_no,
                            for dot in range(3):
                                print '.',
                                time.sleep(1)
                            if "Rejected : Can't submit your message, finished your day quota." not in page:
                                if self.successfully_sent(mobile_no, string):
                                    print 'sent successfully.'
                                else:
                                    print 'failed to send.'
                            else:
                                print 'quota finished!'
                                sys.exit(1)
    def logout(self):
        self.ses.get(self.new_url+'main.action')
        try:
            os.remove('.token')
        finally:
            print 'Log-out!'
            sys.exit(0)       
if __name__ == '__main__':
   
        Way2sms().sms()
        Way2sms().logout()
================================


Friday, 20 October 2017

How to install scipy in windows operating system

U can find pip and easy_install in
C:/Python27/Scripts
Double click on pip or easy_install

Then Go to CMD and go to path
C:/Python27/Scripts

and then use easy_install
or
pip

Include the path C:/Python27/Scripts in your PATH system environment variable.

In Windows you cannot install scipy using pip or any online tool..
So download scipy from the below url
http://www.lfd.uci.edu/~gohlke/pythonlibs/

download scipy-0.19.1-cp27-cp27m-win32.whl if you are using python 2.7 32 bit installation
here in the scipy file name cp27 means python version 2.7 and
save the scipy file to your python directory i.e, C:/>Python27 in case of mine
Then type the following command in CMD
pip install scipy-0.19.1-cp27-cp27m-win32.whl
===================================================================
(to know whether you are using python 32 bit or 64 bit installation.
in CMD type Python and
it will show u
For me it is 32 bit installation as shown below...COME out of Python prompt by pressing CTRL+Z)

http://scikit-learn-general.narkive.com/VfmKliBR/easy-way-to-handle-arff-files-in-sklearn

==========================================

 To open idle in python:

idle python_file.py & disown

 

Friday, 19 May 2017

Converting Excel data to learn Machine learning using Scikit-learn python

If you have suprevised data in EXCEL and you want to do machine learning on that data as given in the below link
http://scikit-learn.org/stable/auto_examples/model_selection/plot_roc.html

u need to convert the excel data into a format required in the link X, y arrays.
here in the link X is a 2 dimensional numpy float array and y is one dimensional numpy array


For ex: if u have data as shown below

fishlength       fishwidth   classlabel
1.2                   1.4                 1
1.5                   4.3                 2

We require X=array([[ 1.2 ,   1.4],[ 1.5,4.3]]) and y=array([1,2])
inorder to convert that data into the above format as required in the link

In the excel sheets remove the headers (fishlength ,fishwidth, classlabel) and cut the classlabel entire column and save it as .csv(comma delimited ) in the SAVE AS dialog box (for ex: here the filename is finaldata.csv)


and paste the classlabel column in seperate excel workbook using PasteSpecial and choosing transpose option in PasteSpecial.
Save this workbook with .csv(comma delimited ) in the SAVE AS dialog box(for ex: here the filename is label.csv)

type the below code:

import csv
import numpy as np
f=open("finaldata.csv")
X=np.genfromtxt(f,delimiter=",")
f.close()
f=open('label.csv')
csv=np.genfromtxt(f,delimiter=",")
y=csv.astype(int)
f.close()

#the below code is copied and pasted by removing nosiy features in above link

y = label_binarize(y, classes=[1, 2, 3])#array([[1, 0, 0],[1, 0, 0],...
n_classes = y.shape[1]#shape[1] gives columns (3 here) and y.shape[0] gives rows
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.5)#50% are taken as training data(X_train and those labels as y_train)
classifier = OneVsRestClassifier(svm.SVC(kernel='linear', probability=True))#creating classifier
y_score = classifier.fit(X_train, y_train).decision_function(X_test)#ysocre=array([[ -2.49503189e+00,   4.13933465e-01,   9.99997811e-01],...X_test value belongs to class 3
fpr = dict()
tpr = dict()
roc_auc = dict()
for i in range(n_classes):
    fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_score[:, i])#y_test has actual label information and y_score is predicted fpr=false positive rate
    roc_auc[i] = auc(fpr[i], tpr[i])

# Compute micro-average ROC curve and ROC area
fpr["micro"], tpr["micro"], _ = roc_curve(y_test.ravel(), y_score.ravel())
roc_auc["micro"] = auc(fpr["micro"], tpr["micro"])
plt.figure()
lw = 2
plt.plot(fpr[2], tpr[2], color='darkorange',
         lw=lw, label='ROC curve (area = %0.2f)' % roc_auc[2])
plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic example')
plt.legend(loc="lower right")
plt.show()

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: