Tuesday 30 July 2019

shiny2

library(shiny)
ui<-fluidPage(
  sidebarPanel(
    sliderInput("num","integer",1,200,5,step=1,animate = animationOptions(interval = 1000,loop = TRUE))),
  radioButtons("radio",label = h1("Choose one"),choices = list("Table"=1,"Even/Odd"=2,"Fact"=3),selected = 1),
  hr(),
  mainPanel(
    tableOutput("abc")
  )
)


server<-function(input,output)
{
 
    output$abc<-renderPrint({
      r<-input$radio
      x<-input$num
      if(r==1){
        for(i in 1:10)
        {
          cat(x,"X",i,"=",x*i,"<br>")
        }
      }else if(r==2)
      {
        if(x%%2==0)
        {
          print("Even")
        }else{
          print("Odd")
        }
      }
      else{
        print(factorial(x))
      }
    })
   
}   
   
shinyApp(ui=ui,server=server)

Shiny1

library(shiny)
ui <- fluidPage(
   titlePanel("TABLE"),
    sidebarLayout(
      sidebarPanel(
        sliderInput("num", "integer", 1, 20, 1,
                    step = 1, animate =
                      animationOptions(interval=400, loop=TRUE))),
      mainPanel(
        tableOutput("prod")
      )) )


server <- function(input, output) {
    output$prod <- renderPrint({ x<-input$num
    for(i in 1:10){
      a=x*i
      cat(x,"x",i,"=",a,"<br>")
       }})}

shinyApp(ui = ui, server = server)

Friday 26 July 2019

Real time object detection


import cv2
import numpy as np
cam = cv2.VideoCapture(0)
cv2.namedWindow("test")
img_counter = 0
while True:
    ret, frame = cam.read()
    cv2.imshow("test", frame)
    if not ret:
        break
    k = cv2.waitKey(1)
    if k%256 == 27:
        # ESC pressed
print("Escape hit, closing...")
        break
elif k%256 == 32:
        # SPACE pressed
img_name = "opencv_frame_{}.png".format(img_counter)
        cv2.imwrite(img_name, frame)
print("{} written!".format(img_name))
img_counter += 1
cam.release()
cv2.destroyAllWindows()

Wednesday 24 July 2019

GUI with Python

# import openpyxl and tkinter modules
from openpyxl import *
from tkinter import *
 
# globally declare wb and sheet variable
 
# opening the existing excel file
wb = load_workbook('C:\\Users\\Manish\\Desktop\\excel.xlsx')
 
# create the sheet object
sheet = wb.active
 
 
def excel():
     
    # resize the width of columns in
    # excel spreadsheet
    sheet.column_dimensions['A'].width = 30
    sheet.column_dimensions['B'].width = 10
    sheet.column_dimensions['C'].width = 10
    sheet.column_dimensions['D'].width = 20
    sheet.column_dimensions['E'].width = 20
    sheet.column_dimensions['F'].width = 40
    sheet.column_dimensions['G'].width = 50
 
    # write given data to an excel spreadsheet
    # at particular location
    sheet.cell(row=1, column=1).value = "Name"
    sheet.cell(row=1, column=2).value = "Course"
    sheet.cell(row=1, column=3).value = "Semester"
    sheet.cell(row=1, column=4).value = "Form Number"
    sheet.cell(row=1, column=5).value = "Contact Number"
    sheet.cell(row=1, column=6).value = "Email id"
    sheet.cell(row=1, column=7).value = "Address"
 
 
# Function to set focus (cursor)
def focus1(event):
    # set focus on the course_field box
    course_field.focus_set()
 
 
# Function to set focus
def focus2(event):
    # set focus on the sem_field box
    sem_field.focus_set()
 
 
# Function to set focus
def focus3(event):
    # set focus on the form_no_field box
    form_no_field.focus_set()
 
 
# Function to set focus
def focus4(event):
    # set focus on the contact_no_field box
    contact_no_field.focus_set()
 
 
# Function to set focus
def focus5(event):
    # set focus on the email_id_field box
    email_id_field.focus_set()
 
 
# Function to set focus
def focus6(event):
    # set focus on the address_field box
    address_field.focus_set()
 
 
# Function for clearing the
# contents of text entry boxes
def clear():
     
    # clear the content of text entry box
    name_field.delete(0, END)
    course_field.delete(0, END)
    sem_field.delete(0, END)
    form_no_field.delete(0, END)
    contact_no_field.delete(0, END)
    email_id_field.delete(0, END)
    address_field.delete(0, END)
 
 
# Function to take data from GUI 
# window and write to an excel file
def insert():
     
    # if user not fill any entry
    # then print "empty input"
    if (name_field.get() == "" and
        course_field.get() == "" and
        sem_field.get() == "" and
        form_no_field.get() == "" and
        contact_no_field.get() == "" and
        email_id_field.get() == "" and
        address_field.get() == ""):
             
        print("empty input")
 
    else:
 
        # assigning the max row and max column
        # value upto which data is written
        # in an excel sheet to the variable
        current_row = sheet.max_row
        current_column = sheet.max_column
 
        # get method returns current text
        # as string which we write into
        # excel spreadsheet at particular location
        sheet.cell(row=current_row + 1, column=1).value = name_field.get()
        sheet.cell(row=current_row + 1, column=2).value = course_field.get()
        sheet.cell(row=current_row + 1, column=3).value = sem_field.get()
        sheet.cell(row=current_row + 1, column=4).value = form_no_field.get()
        sheet.cell(row=current_row + 1, column=5).value = contact_no_field.get()
        sheet.cell(row=current_row + 1, column=6).value = email_id_field.get()
        sheet.cell(row=current_row + 1, column=7).value = address_field.get()
 
        # save the file
        wb.save('C:\\Users\\Manish\\Desktop\\excel.xlsx')
 
        # set focus on the name_field box
        name_field.focus_set()
 
        # call the clear() function
        clear()
 
 
# Driver code
if __name__ == "__main__":
     
    # create a GUI window
    root = Tk()
 
    # set the background colour of GUI window
    root.configure(background='light green')
 
    # set the title of GUI window
    root.title("registration form")
 
    # set the configuration of GUI window
    root.geometry("500x300")
 
    excel()
 
    # create a Form label
    heading = Label(root, text="Form", bg="light green")
 
    # create a Name label
    name = Label(root, text="Name", bg="light green")
 
    # create a Course label
    course = Label(root, text="Course", bg="light green")
 
    # create a Semester label
    sem = Label(root, text="Semester", bg="light green")
 
    # create a Form No. lable
    form_no = Label(root, text="Form No.", bg="light green")
 
    # create a Contact No. label
    contact_no = Label(root, text="Contact No.", bg="light green")
 
    # create a Email id label
    email_id = Label(root, text="Email id", bg="light green")
 
    # create a address label
    address = Label(root, text="Address", bg="light green")
 
    # grid method is used for placing
    # the widgets at respective positions
    # in table like structure .
    heading.grid(row=0, column=1)
    name.grid(row=1, column=0)
    course.grid(row=2, column=0)
    sem.grid(row=3, column=0)
    form_no.grid(row=4, column=0)
    contact_no.grid(row=5, column=0)
    email_id.grid(row=6, column=0)
    address.grid(row=7, column=0)
 
    # create a text entry box
    # for typing the information
    name_field = Entry(root)
    course_field = Entry(root)
    sem_field = Entry(root)
    form_no_field = Entry(root)
    contact_no_field = Entry(root)
    email_id_field = Entry(root)
    address_field = Entry(root)
 
    # bind method of widget is used for
    # the binding the function with the events
 
    # whenever the enter key is pressed
    # then call the focus1 function
    name_field.bind("<Return>", focus1)
 
    # whenever the enter key is pressed
    # then call the focus2 function
    course_field.bind("<Return>", focus2)
 
    # whenever the enter key is pressed
    # then call the focus3 function
    sem_field.bind("<Return>", focus3)
 
    # whenever the enter key is pressed
    # then call the focus4 function
    form_no_field.bind("<Return>", focus4)
 
    # whenever the enter key is pressed
    # then call the focus5 function
    contact_no_field.bind("<Return>", focus5)
 
    # whenever the enter key is pressed
    # then call the focus6 function
    email_id_field.bind("<Return>", focus6)
 
    # grid method is used for placing
    # the widgets at respective positions
    # in table like structure .
    name_field.grid(row=1, column=1, ipadx="100")
    course_field.grid(row=2, column=1, ipadx="100")
    sem_field.grid(row=3, column=1, ipadx="100")
    form_no_field.grid(row=4, column=1, ipadx="100")
    contact_no_field.grid(row=5, column=1, ipadx="100")
    email_id_field.grid(row=6, column=1, ipadx="100")
    address_field.grid(row=7, column=1, ipadx="100")
 
    # call excel function
    excel()
 
    # create a Submit Button and place into the root window
    submit = Button(root, text="Submit", fg="Black",
                            bg="Red", command=insert)
    submit.grid(row=8, column=1)
 
    # start the GUI
    root.mainloop() 

ANN



import numpy as np 
feature_set = np.array([[0,1,0],[0,0,1],[1,0,0],[1,1,0],[1,1,1]]) 
labels = np.array([[1,0,0,1,1]]) 
labels = labels.reshape(5,1)


# In[3]:


labels


# In[8]:


#define hyper parameters for our neural network

np.random.seed(42)  #random.seed function so that we can get the same random values whenever the script is executed.
weights = np.random.rand(3,1) 
bias = np.random.rand(1) 
lr = 0.05


# In[9]:


weights  #Return a sample (or samples) from the “standard normal” distribution( “normal” (Gaussian) distribution of mean 0 and variance 1)


# In[10]:


bias #Create an array of the given shape and populate it with random samples from a uniform distribution over [0, 1)


# In[11]:


lr # learning rate


# In[12]:


def sigmoid(x):    #activation function is the sigmoid function
    return 1/(1+np.exp(-x))


# In[13]:


def sigmoid_der(x):    #calculates the derivative of the sigmoid function
    return sigmoid(x)*(1-sigmoid(x))


# In[14]:


#train our neural network that will be able to predict whether a person is obese or not.

# An epoch is basically the number of times we want to train the algorithm on our data.
#We will train the algorithm on our data 20,000 times. The ultimate goal is to minimize the error.

for epoch in range(20000): 
    inputs = feature_set

#Here we find the dot product of the input and the weight vector and add bias to it.

    # feedforward step1
    XW = np.dot(feature_set, weights) + bias
   
#We pass the dot product through the sigmoid activation function

    #feedforward step2
    z = sigmoid(XW)
   
#The variable z contains the predicted outputs. The first step of the backpropagation is to find the error.

    # backpropagation step 1
    error = z - labels

    print(error.sum())

    # backpropagation step 2
    dcost_dpred = error
    dpred_dz = sigmoid_der(z)
   
#Here we have the z_delta variable, which contains the product of dcost_dpred and dpred_dz.
#Instead of looping through each record and multiplying the input with corresponding z_delta,
#we take the transpose of the input feature matrix and multiply it with the z_delta.
#Finally, we multiply the learning rate variable lr with the derivative to increase the speed of convergence.

    z_delta = dcost_dpred * dpred_dz

    inputs = feature_set.T
    weights -= lr * np.dot(inputs, z_delta)

    for num in z_delta:
        bias -= lr * num


# In[15]:


#You can see that error is extremely small at the end of the training of our neural network.
#At this point of time our weights and bias will have values that can be used to detect whether a person is diabetic or not,
#based on his smoking habits, obesity, and exercise habits.

#TEST : suppose we have a record of a patient that comes in who smokes, is not obese, and doesn't exercise.
#Let's find if he is likely to be diabetic or not. The input feature will look like this: [1,0,0].

single_point = np.array([1,0,0]) 
result = sigmoid(np.dot(single_point, weights) + bias) 
print(result)


# In[ ]:


#You can see that the person is likely not diabetic since the value is much closer to 0 than 1.


# In[16]:


#let's test another person who doesn't, smoke, is obese, and doesn't exercises. The input feature vector will be [0,1,0]

single_point = np.array([0,1,0]) 
result = sigmoid(np.dot(single_point, weights) + bias) 
print(result) 


# In[18]:


#value is very close to 1, which is likely due to the person's obesity.
#Multiply the result by 100 percent to convert the accuracy to a percentage. For our thermometer example:
#Relative accuracy = Accuracy x 100 percent = 0.968 x 100 percent = 96.8 percent

A=0.00707584 * 100
B=0.99837029 * 100
print(A)
print(B)

Reg2 GUI

from pandas import DataFrame
from sklearn import linear_model
import tkinter as tk
import statsmodels.api as sm

Stock_Market = {'Year': [2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016],
                'Month': [12, 11,10,9,8,7,6,5,4,3,2,1,12,11,10,9,8,7,6,5,4,3,2,1],
                'Interest_Rate': [2.75,2.5,2.5,2.5,2.5,2.5,2.5,2.25,2.25,2.25,2,2,2,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75],
                'Unemployment_Rate': [5.3,5.3,5.3,5.3,5.4,5.6,5.5,5.5,5.5,5.6,5.7,5.9,6,5.9,5.8,6.1,6.2,6.1,6.1,6.1,5.9,6.2,6.2,6.1],
                'Stock_Index_Price': [1464,1394,1357,1293,1256,1254,1234,1195,1159,1167,1130,1075,1047,965,943,958,971,949,884,866,876,822,704,719]       
                }


df = DataFrame(Stock_Market,columns=['Year','Month','Interest_Rate','Unemployment_Rate','Stock_Index_Price'])

X = df[['Interest_Rate','Unemployment_Rate']] # here we have 2 input variables for multiple regression. If you just want to use one variable for simple linear regression, then use X = df['Interest_Rate'] for example.Alternatively, you may add additional variables within the brackets
Y = df['Stock_Index_Price'] # output variable (what we are trying to predict)

# with sklearn
regr = linear_model.LinearRegression()
regr.fit(X, Y)

print('Intercept: \n', regr.intercept_)
print('Coefficients: \n', regr.coef_)


# with statsmodels
X = sm.add_constant(X) # adding a constant

model = sm.OLS(Y, X).fit()
predictions = model.predict(X)



# tkinter GUI
root= tk.Tk()

canvas1 = tk.Canvas(root, width = 1200, height = 450)
canvas1.pack()

# with sklearn
Intercept_result = ('Intercept: ', regr.intercept_)
label_Intercept = tk.Label(root, text=Intercept_result, justify = 'center')
canvas1.create_window(260, 220, window=label_Intercept)

# with sklearn
Coefficients_result  = ('Coefficients: ', regr.coef_)
label_Coefficients = tk.Label(root, text=Coefficients_result, justify = 'center')
canvas1.create_window(260, 240, window=label_Coefficients)

# with statsmodels
print_model = model.summary()
label_model = tk.Label(root, text=print_model, justify = 'center', relief = 'solid', bg='LightSkyBlue1')
canvas1.create_window(800, 220, window=label_model)


# New_Interest_Rate label and input box
label1 = tk.Label(root, text='Type Interest Rate: ')
canvas1.create_window(100, 100, window=label1)

entry1 = tk.Entry (root) # create 1st entry box
canvas1.create_window(270, 100, window=entry1)

# New_Unemployment_Rate label and input box
label2 = tk.Label(root, text=' Type Unemployment Rate: ')
canvas1.create_window(120, 120, window=label2)

entry2 = tk.Entry (root) # create 2nd entry box
canvas1.create_window(270, 120, window=entry2)


def values():
    global New_Interest_Rate #our 1st input variable
    New_Interest_Rate = float(entry1.get())
   
    global New_Unemployment_Rate #our 2nd input variable
    New_Unemployment_Rate = float(entry2.get())
   
    Prediction_result  = ('Predicted Stock Index Price: ', regr.predict([[New_Interest_Rate ,New_Unemployment_Rate]]))
    label_Prediction = tk.Label(root, text= Prediction_result, bg='orange')
    canvas1.create_window(260, 280, window=label_Prediction)
   
button1 = tk.Button (root, text='Predict Stock Index Price',command=values, bg='orange') # button to call the 'values' command above
canvas1.create_window(270, 150, window=button1)


root.mainloop()

GUI reg

from pandas import DataFrame
from sklearn import linear_model
import tkinter as tk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

Stock_Market = {'Year': [2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016],
                'Month': [12, 11,10,9,8,7,6,5,4,3,2,1,12,11,10,9,8,7,6,5,4,3,2,1],
                'Interest_Rate': [2.75,2.5,2.5,2.5,2.5,2.5,2.5,2.25,2.25,2.25,2,2,2,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75],
                'Unemployment_Rate': [5.3,5.3,5.3,5.3,5.4,5.6,5.5,5.5,5.5,5.6,5.7,5.9,6,5.9,5.8,6.1,6.2,6.1,6.1,6.1,5.9,6.2,6.2,6.1],
                'Stock_Index_Price': [1464,1394,1357,1293,1256,1254,1234,1195,1159,1167,1130,1075,1047,965,943,958,971,949,884,866,876,822,704,719]       
                }

df = DataFrame(Stock_Market,columns=['Year','Month','Interest_Rate','Unemployment_Rate','Stock_Index_Price'])

X = df[['Interest_Rate','Unemployment_Rate']].astype(float) # here we have 2 input variables for multiple regression. If you just want to use one variable for simple linear regression, then use X = df['Interest_Rate'] for example.Alternatively, you may add additional variables within the brackets
Y = df['Stock_Index_Price'].astype(float) # output variable (what we are trying to predict)

# with sklearn
regr = linear_model.LinearRegression()
regr.fit(X, Y)

print('Intercept: \n', regr.intercept_)
print('Coefficients: \n', regr.coef_)


# tkinter GUI
root= tk.Tk()

canvas1 = tk.Canvas(root, width = 500, height = 300)
canvas1.pack()

# with sklearn
Intercept_result = ('Intercept: ', regr.intercept_)
label_Intercept = tk.Label(root, text=Intercept_result, justify = 'center')
canvas1.create_window(260, 220, window=label_Intercept)

# with sklearn
Coefficients_result  = ('Coefficients: ', regr.coef_)
label_Coefficients = tk.Label(root, text=Coefficients_result, justify = 'center')
canvas1.create_window(260, 240, window=label_Coefficients)


# New_Interest_Rate label and input box
label1 = tk.Label(root, text='Type Interest Rate: ')
canvas1.create_window(100, 100, window=label1)

entry1 = tk.Entry (root) # create 1st entry box
canvas1.create_window(270, 100, window=entry1)

# New_Unemployment_Rate label and input box
label2 = tk.Label(root, text=' Type Unemployment Rate: ')
canvas1.create_window(120, 120, window=label2)

entry2 = tk.Entry (root) # create 2nd entry box
canvas1.create_window(270, 120, window=entry2)


def values():
    global New_Interest_Rate #our 1st input variable
    New_Interest_Rate = float(entry1.get())
   
    global New_Unemployment_Rate #our 2nd input variable
    New_Unemployment_Rate = float(entry2.get())
   
    Prediction_result  = ('Predicted Stock Index Price: ', regr.predict([[New_Interest_Rate ,New_Unemployment_Rate]]))
    label_Prediction = tk.Label(root, text= Prediction_result, bg='orange')
    canvas1.create_window(260, 280, window=label_Prediction)
   
button1 = tk.Button (root, text='Predict Stock Index Price',command=values, bg='orange') # button to call the 'values' command above
canvas1.create_window(270, 150, window=button1)


#plot 1st scatter
figure3 = plt.Figure(figsize=(5,4), dpi=100)
ax3 = figure3.add_subplot(111)
ax3.scatter(df['Interest_Rate'].astype(float),df['Stock_Index_Price'].astype(float), color = 'r')
scatter3 = FigureCanvasTkAgg(figure3, root)
scatter3.get_tk_widget().pack(side=tk.RIGHT, fill=tk.BOTH)
ax3.legend()
ax3.set_xlabel('Interest Rate')
ax3.set_title('Interest Rate Vs. Stock Index Price')

#plot 2nd scatter
figure4 = plt.Figure(figsize=(5,4), dpi=100)
ax4 = figure4.add_subplot(111)
ax4.scatter(df['Unemployment_Rate'].astype(float),df['Stock_Index_Price'].astype(float), color = 'g')
scatter4 = FigureCanvasTkAgg(figure4, root)
scatter4.get_tk_widget().pack(side=tk.RIGHT, fill=tk.BOTH)
ax4.legend()
ax4.set_xlabel('Unemployment_Rate')
ax4.set_title('Unemployment_Rate Vs. Stock Index Price')

root.mainloop()

Tuesday 23 July 2019

smile det

import cv2

faceCascade = cv2.CascadeClassifier('D:\\opencv\\OpenCV Final Softwares\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_alt.xml')
smileCascade= cv2.CascadeClassifier('D:\\opencv\\OpenCV Final Softwares\\opencv\\sources\\data\\haarcascades\\haarcascade_smile.xml')

# grab the reference to the webcam
vs = cv2.VideoCapture(0)

# keep looping
while True:
# grab the current frame
ret, frame = vs.read()
 
# if we are viewing a video and we did not grab a frame,
# then we have reached the end of the video
if frame is None:
break

gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray = cv2.equalizeHist(gray)

faces = faceCascade.detectMultiScale(frame, scaleFactor=1.05, minNeighbors=5, minSize=(45, 45))

for (x,y,w,h) in faces:
#cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
face_gray = gray[y:y+h, x:x+w]
face_color = frame[y:y+h, x:x+w]
smiles = smileCascade.detectMultiScale(face_gray, scaleFactor=1.7, minNeighbors=3, minSize=(15, 15))
for (ex,ey,ew,eh) in smiles:
cv2.rectangle(face_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),1)

# show the frame to our screen
cv2.imshow("Video", frame)
key = cv2.waitKey(1) & 0xFF

# if the 'q' key is pressed, stop the loop
if key == ord("q"):
break

# close all windows
cv2.destroyAllWindows()

face det

import cv2

faceCascade = cv2.CascadeClassifier('D:\\opencv\\OpenCV Final Softwares\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_default.xml')

# grab the reference to the webcam
vs = cv2.VideoCapture(0)

# keep looping
while True:
# grab the current frame
ret, frame = vs.read()
 
# if we are viewing a video and we did not grab a frame,
# then we have reached the end of the video
if frame is None:
break

faces = faceCascade.detectMultiScale(frame)

for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (255,0,0), 2)

# show the frame to our screen
cv2.imshow("Video", frame)
key = cv2.waitKey(1) & 0xFF

# if the 'q' key is pressed, stop the loop
if key == ord("q"):
break

# close all windows
cv2.destroyAllWindows()

Face det webcam

import face_recognition
import cv2
import numpy as np

# Get a reference to webcam #0 (the default one)
video_capture = cv2.VideoCapture(0)

# Load a sample picture and learn how to recognize it.
obama_image = face_recognition.load_image_file("obama.jpg")
obama_face_encoding = face_recognition.face_encodings(obama_image)[0]

# Load a second sample picture and learn how to recognize it.
biden_image = face_recognition.load_image_file("biden.jpg")
biden_face_encoding = face_recognition.face_encodings(biden_image)[0]

# Create arrays of known face encodings and their names
known_face_encodings = [
    obama_face_encoding,
    biden_face_encoding
]
known_face_names = [
    "Barack Obama",
    "Joe Biden"
]

# Initialize some variables
face_locations = []
face_encodings = []
face_names = []
process_this_frame = True

while True:
    # Grab a single frame of video
    ret, frame = video_capture.read()

    # Resize frame of video to 1/4 size for faster face recognition processing
    small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)

    # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
    rgb_small_frame = small_frame[:, :, ::-1]

    # Only process every other frame of video to save time
    if process_this_frame:
        # Find all the faces and face encodings in the current frame of video
        face_locations = face_recognition.face_locations(rgb_small_frame)
        face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)

        face_names = []
        for face_encoding in face_encodings:
            # See if the face is a match for the known face(s)
            matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
            name = "Unknown"

            # # If a match was found in known_face_encodings, just use the first one.
            # if True in matches:
            #     first_match_index = matches.index(True)
            #     name = known_face_names[first_match_index]

            # Or instead, use the known face with the smallest distance to the new face
            face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
            best_match_index = np.argmin(face_distances)
            if matches[best_match_index]:
                name = known_face_names[best_match_index]

            face_names.append(name)

    process_this_frame = not process_this_frame


    # Display the results
    for (top, right, bottom, left), name in zip(face_locations, face_names):
        # Scale back up face locations since the frame we detected in was scaled to 1/4 size
        top *= 4
        right *= 4
        bottom *= 4
        left *= 4

        # Draw a box around the face
        cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)

        # Draw a label with a name below the face
        cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
        font = cv2.FONT_HERSHEY_DUPLEX
        cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)

    # Display the resulting image
    cv2.imshow('Video', frame)

    # Hit 'q' on the keyboard to quit!
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Release handle to the webcam
video_capture.release()
cv2.destroyAllWindows()

link for project

merge with color

import cv2

img = cv2.imread('lena.jpg')

#Split function splits the image into each color index

B,G,R = cv2.split(img)

cv2.imshow('RGB Image', img)

cv2.imshow('Red Channel ', R)
cv2.imshow('Green Channel ', G)
cv2.imshow('Blue Channel ', B)

cv2.waitKey(0)
cv2.destroyAllWindows()


# Let's remake the original image
merged = cv2.merge([B, G, R])
cv2.imshow('Merged', merged)


#Lets apply the blue color

merged1 = cv2.merge([B+100, G, R])
cv2.imshow('Merged with Blue', merged1)

cv2.waitKey(0)
cv2.destroyAllWindows()

Hand opencv

# Imports
import numpy as np
import cv2
import math

# Open Camera
capture = cv2.VideoCapture(0)

while capture.isOpened():

    # Capture frames from the camera
    ret, frame = capture.read()

    # Get hand data from the rectangle sub window
    cv2.rectangle(frame, (100, 100), (300, 300), (0, 255, 0), 0)
    crop_image = frame[100:300, 100:300]

    # Apply Gaussian blur
    blur = cv2.GaussianBlur(crop_image, (3, 3), 0)

    # Change color-space from BGR -> HSV
    hsv = cv2.cvtColor(blur, cv2.COLOR_BGR2HSV)

    # Create a binary image with where white will be skin colors and rest is black
    mask2 = cv2.inRange(hsv, np.array([2, 0, 0]), np.array([20, 255, 255]))

    # Kernel for morphological transformation
    kernel = np.ones((5, 5))

    # Apply morphological transformations to filter out the background noise
    dilation = cv2.dilate(mask2, kernel, iterations=1)
    erosion = cv2.erode(dilation, kernel, iterations=1)

    # Apply Gaussian Blur and Threshold
    filtered = cv2.GaussianBlur(erosion, (3, 3), 0)
    ret, thresh = cv2.threshold(filtered, 127, 255, 0)

    # Show threshold image
    cv2.imshow("Thresholded", thresh)

    # Find contours
    contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    try:
        # Find contour with maximum area
        contour = max(contours, key=lambda x: cv2.contourArea(x))

        # Create bounding rectangle around the contour
        x, y, w, h = cv2.boundingRect(contour)
        cv2.rectangle(crop_image, (x, y), (x + w, y + h), (0, 0, 255), 0)

        # Find convex hull
        hull = cv2.convexHull(contour)

        # Draw contour
        drawing = np.zeros(crop_image.shape, np.uint8)
        cv2.drawContours(drawing, [contour], -1, (0, 255, 0), 0)
        cv2.drawContours(drawing, [hull], -1, (0, 0, 255), 0)

        # Find convexity defects
        hull = cv2.convexHull(contour, returnPoints=False)
        defects = cv2.convexityDefects(contour, hull)

        # Use cosine rule to find angle of the far point from the start and end point i.e. the convex points (the finger
        # tips) for all defects
        count_defects = 0

        for i in range(defects.shape[0]):
            s, e, f, d = defects[i, 0]
            start = tuple(contour[s][0])
            end = tuple(contour[e][0])
            far = tuple(contour[f][0])

            a = math.sqrt((end[0] - start[0]) ** 2 + (end[1] - start[1]) ** 2)
            b = math.sqrt((far[0] - start[0]) ** 2 + (far[1] - start[1]) ** 2)
            c = math.sqrt((end[0] - far[0]) ** 2 + (end[1] - far[1]) ** 2)
            angle = (math.acos((b ** 2 + c ** 2 - a ** 2) / (2 * b * c)) * 180) / 3.14

            # if angle > 90 draw a circle at the far point
            if angle <= 90:
                count_defects += 1
                cv2.circle(crop_image, far, 1, [0, 0, 255], -1)

            cv2.line(crop_image, start, end, [0, 255, 0], 2)

        # Print number of fingers
        if count_defects == 0:
            cv2.putText(frame, "ONE", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 2,(0,0,255),2)
        elif count_defects == 1:
            cv2.putText(frame, "TWO", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 2,(0,0,255), 2)
        elif count_defects == 2:
            cv2.putText(frame, "THREE", (5, 50), cv2.FONT_HERSHEY_SIMPLEX, 2,(0,0,255), 2)
        elif count_defects == 3:
            cv2.putText(frame, "FOUR", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 2,(0,0,255), 2)
        elif count_defects == 4:
            cv2.putText(frame, "FIVE", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 2,(0,0,255), 2)
        else:
            pass
    except:
        pass

    # Show required images
    cv2.imshow("Gesture", frame)
    all_image = np.hstack((drawing, crop_image))
    cv2.imshow('Contours', all_image)

    # Close the camera if 'q' is pressed
    if cv2.waitKey(1) == ord('q'):
        break

capture.release()
cv2.destroyAllWindows()

Image from webcam


import cv2
import numpy as np
cam = cv2.VideoCapture(0)
cv2.namedWindow("test")
img_counter = 0
while True:
    ret, frame = cam.read()
    cv2.imshow("test", frame)
    if not ret:
        break
    k = cv2.waitKey(1)
    if k%256 == 27:
        # ESC pressed
print("Escape hit, closing...")
        break
elif k%256 == 32:
        # SPACE pressed
img_name = "opencv_frame_{}.png".format(img_counter)
        cv2.imwrite(img_name, frame)
print("{} written!".format(img_name))
img_counter += 1
cam.release()
cv2.destroyAllWindows()

Monday 22 July 2019

dataset

https://drive.google.com/open?id=1oD1mFi4zmqz5xGuCJ7_OdUKZgW5fekct


https://drive.google.com/file/d/1M4sGfss3DLYosCxWZoai2i9X1AMZoolb/view?usp=sharing

UDF in Python


def add(x, y):
   return x + y

# This function subtracts two numbers
def subtract(x, y):
   return x - y

# This function multiplies two numbers
def multiply(x, y):
   return x * y

# This function divides two numbers
def divide(x, y):
   return x / y

print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

# Take input from the user
choice = input("Enter choice(1/2/3/4):")

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

if choice == '1':
   print(num1,"+",num2,"=", add(num1,num2))

elif choice == '2':
   print(num1,"-",num2,"=", subtract(num1,num2))

elif choice == '3':
   print(num1,"*",num2,"=", multiply(num1,num2))

elif choice == '4':
   print(num1,"/",num2,"=", divide(num1,num2))
else:
   print("Invalid input")

Dict

dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': ‘RAM','code:8989:, 'dept': ‘IT'}
print(dict['one']) # Prints value for 'one' key
print(dict[2]) # Prints value for 2 key
print(tinydict) # Prints complete dictionary
print(tinydict.keys()) # Prints all the keys
print(tinydict.values()) # Prints all the values

Tuple

tuple = (‘xyz', 123, 1.23, ‘RAM', 17.5 )
tinytuple = (123, ‘RAM‘)
print(tuple) # Prints complete list
print(tuple[0]) # Prints first element of the list
print(tuple[1:3]) # Prints elements starting from 2nd till 3rd
print(tuple[2:]) # Prints elements starting from 3rd element
print(tinytuple * 2) # Prints list two times
print (tuple + tinytuple) # Prints concatenated lists
tuple.append(‘Manish’) # Not Applicable

list


list = [ ‘xyz', 123, 1.23, ‘RAM', 17.5 ]
tinylist = [123, ‘RAM']
print(list) # Prints complete list
print(list[0]) # Prints first element of the list
print(list[1:3]) # Prints elements starting from 2nd till 3rd
print(list[2:]) # Prints elements starting from 3rd element
print(tinylist * 2) # Prints list two times
print(list + tinylist) # Prints concatenated lists
list.append(“Manish”) #Applicable
print(“list[3:] = ", list[3:])