Search This Blog

Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Monday, 18 November 2024

Step-by-step guide to getting started with TensorFlow, an open-source machine learning library

 


                            TensorFlow First Model

Introduction

TensorFlow is an open-source machine learning library developed by Google. It is used for a wide range of machine learning tasks, including image classification, object detection, natural language processing, and time series analysis.

Uses of this Project

  • Build and train machine learning models
  • Deploy machine learning models to production
  • Develop new machine learning algorithms
  • Contribute to the TensorFlow community

Requirements

  • Python 3.6 or later
  • TensorFlow 2.0 or later
  • A text editor or IDE

Getting Started

To get started with this project, you will need to install TensorFlow and create a new Python project.

Installing TensorFlow

pip install tensorflow

Creating a New Python Project

mkdir my_project
cd my_project
python3 -m venv venv
source venv/bin/activate

Creating Your First Model

Now that you have TensorFlow installed and a new Python project created, you can create your first model.

import tensorflow as tf

# Create a simple model
model = tf.keras.models.Sequential([
  tf.keras.layers.Dense(units=10, activation='relu', input_shape=(784,)),
  tf.keras.layers.Dense(units=10, activation='relu'),
  tf.keras.layers.Dense(units=10, activation='softmax')
])

# Compile the model
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# Train the model
model.fit(x_train, y_train, epochs=10)

# Evaluate the model
model.evaluate(x_test, y_test)

Next Steps

Now that you have created your first model, you can explore the many other features that TensorFlow has to offer. Here are a few ideas for next steps:

  • Learn more about the different types of machine learning models that you can build with TensorFlow.
  • Explore the TensorFlow documentation to learn how to use the library's many features.
  • Contribute to the TensorFlow community by sharing your projects and ideas.

Conclusion

TensorFlow is a powerful machine learning library that can be used to build a wide range of machine learning models. This tutorial has provided you with a basic introduction to TensorFlow. To learn more, please refer to the TensorFlow documentation and explore the many resources that are available online. ```

**TensorFlow Project Tutorial** This comprehensive tutorial provides a step-by-step guide to getting started with TensorFlow, an open-source machine learning library. It covers the basics of installing TensorFlow, creating a new Python project, and building your first machine learning model. The tutorial also includes sections on the uses of TensorFlow, the requirements for using it, and next steps for further learning. This tutorial is suitable for beginners who are new to TensorFlow and want to learn how to use it to build machine learning models. It provides clear and concise instructions, as well as code examples, to help you get started quickly.

Adding Sound and Music to Pygame Games


 

Adding Sound and Music to Pygame Games

Introduction

Sound and music can greatly enhance the user experience in Pygame games. They can create atmosphere, provide feedback, and even affect gameplay. In this tutorial, we'll show you how to add sound effects and music to your Pygame games.

Uses of Sound and Music

There are many ways to use sound and music in Pygame games. Here are a few examples:

  • Sound effects: Sound effects can be used to provide feedback to the player, such as when a character jumps, shoots, or gets hit. They can also be used to create atmosphere, such as the sound of rain or wind.
  • Music: Music can be used to create atmosphere and set the mood for the game. It can also be used to provide a sense of urgency or excitement.

Requirements

To add sound and music to your Pygame games, you will need the following:

  • A sound file in a supported format, such as WAV or OGG.
  • The Pygame library.

Adding Sound Effects

To add a sound effect to your game, you can use the pygame.mixer.Sound() function. This function takes the path to a sound file as its argument. Once you have created a Sound object, you can play it using the play() method.


import pygame

# Create a Sound object
sound = pygame.mixer.Sound('sound.wav')

# Play the sound
sound.play()

Adding Music

To add music to your game, you can use the pygame.mixer.music.load() function. This function takes the path to a music file as its argument. Once you have loaded a music file, you can play it using the play() method.


import pygame

# Load a music file
pygame.mixer.music.load('music.ogg')

# Play the music
pygame.mixer.music.play()

Conclusion

Adding sound and music to your Pygame games is a great way to enhance the user experience. By following the steps outlined in this tutorial, you can easily add sound effects and music to your games.

```

**Adding Sound and Music to Pygame Games** Sound and music can greatly enhance the user experience in Pygame games. They can create atmosphere, provide feedback, and even affect gameplay. In this tutorial, we'll show you how to add sound effects and music to your Pygame games. To add sound effects, you can use the `pygame.mixer.Sound()` function. This function takes the path to a sound file as its argument. Once you have created a `Sound` object, you can play it using the `play()` method. To add music, you can use the `pygame.mixer.music.load()` function. This function takes the path to a music file as its argument. Once you have loaded a music file, you can play it using the `play()` method. Adding sound and music to your Pygame games is a great way to enhance the user experience. By following the steps outlined in this tutorial, you can easily add sound effects and music to your games.

Wednesday, 10 July 2024

Brute Force Password Method in Python

 So hello guys, This blog will guide you how to make a Brute Force program in Python.

Brute Force means Trying one by one each and every character to reach the required password.

Here is the code -

from time import sleep

n = input("Enter here word: ")
chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "
out = ""
for i in range(len(n)):
    for s in chars:
        sleep(0.005)
        print(out+s)
        if s==n[i]:
            out+=s
        if out==n:
            break

Copy this and paste in a new file - file.py 

Thanks, I hope you will get some knowledge           

Wednesday, 8 May 2024

Python Course lesson 1 Printing, user input, comments, modules and Timer and waiting functions

 Here is the code which we studied in Python course 1st lesson

# this line add the function 'sleep' to the program
from time import sleep

# this line takes input from the user
name = input("Your name: ")
 
# this sleep function wait for 1 second ----syntax ---- sleep('seconds')
sleep(1)
print("Waiting 1...")
sleep(1)
print("Waiting 2...")
sleep(1)
print("Waiting 3...")
sleep(1)
print("Waiting 4...")
sleep(1)
print("Waiting 5...")
sleep(1)

# this line print the text which we pass into it, here text is -> name -> name contains the value ' Suryansh ' or whatever you type in input
print(name)

Blink an LED using RaspberryPi pico,nano,3,4,b,b+ in Python and C/C++ both

 

How to Blink an LED on a Raspberry Pi

How to Blink an LED on a Raspberry Pi - Jeremy Morgan's Tech Blog 

The blinking LED is the “hello world” of the maker community, and today I’ll show you how easy it is to do with the Raspberry Pi 2 (or Model B)! We’re going to use Python and WiringPi for this project.

What you’ll need

For this article I’m using a Raspberry Pi 2, but you can also use a Raspberry Pi Model B. You will also need:

  • A GPIO Adapter
  • Breadboard
  • Resistor
  • LED
  • The quickest way to get that LED to blink is to take a look at the pins of the GPIO 

    Raspberry gPIo - learn.sparkfun.com

     and decide which one to tie to. Then you can use Python and the Raspberry Pi GPIO Library to create a script to light it up.

    import RPi.GPIO as GPIO ## Import GPIO Library
    import time ## Import 'time' library (for 'sleep')

    blue = 7 ## These are our LEDs
    ourdelay = 1 ## Delay
    # pins 4,17,18,21,22,23,24,25

    GPIO.setmode(GPIO.BOARD) ## Use BOARD pin numbering
    GPIO.setup(pin, GPIO.OUT) ## set output

    ## function to save code

    def activateLED( pin, delay ):
    GPIO.output(pin, GPIO.HIGH) ## set HIGH (LED ON)
    time.sleep(delay) ## wait
    GPIO.output(pin, GPIO.LOW) ## set LOW (LED OFF)
    return;

    activateLED(blue,ourdelay)

    GPIO.cleanup() ## close down library
    
    

    As you can see in the code above, it doesn’t take much to get things working. But I’ll explain the code a little deeper.

    import RPi.GPIO as GPIO
    import time

    The following code imports the Python GPIO library, and the time library. The GPIO library, as you probably guessed is the library for interacting with the GPIO in Python. It does an amazing job of simplifying the process. The time library is there so we can put a delay in, otherwise the blink might be too fast to notice.

    blue = 7
    ourdelay = 1

    Here I created a variable named “blue” (the color of the LED) and assigned it “7” which is the pin number we want. If I wanted to add multiple LEDs I could name it something like:

    blue = 7
    red = 13
    green 14

    I then created a “delay” variable of one second. This way I can change the delay of the lights blinking however I want.

    You can name the variables anything you want, but this was just to make it easy to see which LED is which if I wanted to do some fancy light show.

    GPIO.setmode(GPIO.BOARD) 

    Then, we set the GPIO mode to “Board” which means we’ll use the numbering of the pin by board instead of GPIO. This makes it a little easier to understand when using a bread board.

    With this line of code we set the pin to be an output:

    GPIO.setup(pin, GPIO.OUT)

    There are 2 main commands to turn the LED on then off:

    GPIO.output(pin, GPIO.HIGH)
    GPIO.output(pin, GPIO.LOW)

    If you wanted to blink an LED twice you would have to repeat the last two lines each time. So I decided to put this in a function and put the pin and delay as parameters. This way making a particular LED blink is as simple as:

    activateLED(blue,ourdelay)

    This is repeatable and saves code when doing larger programs.

    To close everything down, we need to run the following:

    GPIO.cleanup()

    It’s that easy! You could easily write a nice Python script that do some pretty cool stuff with just a few lines of code.

     

    For this step we’ll install WiringPi for the libraries to interact with the GPIO. This allows us to do what we just did, but from the command line. We’ll need to install WiringPi:

    cd ~/sources
    git clone git://git.drogon.net/wiringPi
    cd wiringPi
    git pull origin
    ./build
    
    

    If successful you should see a screen like this:

    Blink an LED Raspberry Pi

    Now we can light up the LED from the command line. Remember the pin 7 in the example above? We can now light up like so:

    gpio mode 7 out
    gpio mode 7 1
    
    

    This will light up the LED. You can turn it off by entering:

    gpio mode 7 0
    
    

    Blink an LED Raspberry Pi

    This makes it super easy to light up LEDs from the command line. You could create a pretty neat BASH script to do this, and do some neat things, or call this from other languages.

    Summary

    I hope this has helped in showing how easy it is to blink an LED on the Raspberry Pi 2/B. Of course as you progress on you’ll want to do far more than just blink an LED, but the GPIO libraries make it very easy to create some neat stuff. If you’ve experimented with this and done something cool, Let me know!!!


Friday, 19 November 2021

Object tracking with OpenCV Python

 Contents:

1) Introduction to the Project
2) Uses of Object Tracking
3) Tools and Softwares used
4) Python Program.

Introduction to the Project:

Object tracking is an application of deep learning where the program takes an initial set of object detections and develops a unique identification for each of the initial detections and then tracks the detected objects as they move around frames in a video.

In other words, object tracking is the task of automatically identifying objects in a video and interpreting them as a set of trajectories with high accuracy

Uses of Object Tracking:

Object tracking is used for a variety of use cases involving different types of input footage. Whether or not the anticipated input will be an image or a video, or a real-time video vs. a prerecorded video, impacts the algorithms used for creating object tracking applications.

The kind of input also impacts the category, use cases, and applications of object tracking. Here, we will briefly describe a few popular uses and types of object tracking, such as video tracking, visual tracking, and image tracking

Tools and Softwares needer:

1) Python 3.x

2) OpenCV-Python

Hardware requirements: Camera


MAIN PROGRAM:


import cv2
cam = cv2.VideoCapture(0)
track = cv2.TrackerCSRT_create()
suc,img=cam.read()
img = cv2.flip(img,1)
bbox = cv2.selectROI("Tracking",img,False)
track.init(img,bbox)

def drawbox(img):
x,y,w,h=int(bbox[0]),int(bbox[1]),int(bbox[2]),int(bbox[3])
cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2)

while 1:
suc,img = cam.read()
img = cv2.flip(img,1)
suc,bbox=track.update(img)
if suc:
drawbox(img)
else:
pass
cv2.imshow("Tracking",img)
if cv2.waitkey(1) & 0xff == ord('q'):
break


Tutorial:




Making your own haarcascade OpenCV Python

What are Haarcascades?


Haar Cascade classifiers are an effective way for object detection. Haar Cascade is a machine learning-based approach where a lot of positive and negative images are used to train the classifier.

  • Positive images – These images contain the images which we want our classifier to identify.
  • Negative Images – Images of everything else, which do not contain the object we want to detect.

Requirements:

Make sure you have python, OpenCV installed on your pc (all the latest versions).
The haar cascade files can be downloaded from the OpenCV Github repository

dasar_haartrain Tool, download from here -> Click Here

Tutorial on How to Train our own haarcascade:


Thursday, 18 November 2021

Mask Detection for COVID-19 disease

Contents:

1) Introduction of the Project
2) Functions and Module Used
3) Software requirements to run the Program
4) Main Program

1) Introduction of the Project

In today’s world, all the things have become
computerized.

As we all know, COVID-19 can spread when
People breathe, talk, cough or sneeze.
Wearing a mask keeps the virus from reaching
Others. It also can stop the virus from reaching
You.

So this program simply Detect all Faces
Camera, then detect Mask on their faces with
The help of Artificial Intelligence (A.1.)
Machine Learning (M.L.).

If someone found without Mask on his/her face
Then “Be Safe Mask not Found” text will be
printed on screen or Custom

required action can be taken by that
Organization who using this Program.

For example: If someone is without Mask then
By using SSH and Arduino this Program will
Close the door or whatever we will set.

2) Functions and Module used:

cv2.VideoCapture(0):

Cv2 is the module for real-time computer vision.
VideoCapture(0) used for capturing frames from
Camera on number (0).

cv2.CascadeClassifier(“Haarcascade.xml”):

This function reads the trained file for
Mask Detection. Haarcascade.xml is the file
contains all Coordinates codings of AI and ML for
Mask Points. We can train this our Own.

cv2.read():

This function reads the frames from Camera
Number (0) which we set above using VideoCapture

detectMultiScale():

This function detect Co-ordinates for Masks which
we trained from above function CascadeClassifer.

cv2.imshow():

This function Displays the Captured Frames which
We captured from cv2.read() function.

3) Software/Hardware Requirements to run the Program:

1) OpenCV-Python, This is Most Important because This is the main library we use in this program
2) Python 3.x, This is required because, I have tested on this only.
3) Pip3, This is required because packages we install will be installed by this program
4) Camera required, We can change this later by using real-time or from saved Image
5) Windows,Linux,Mac any OS support this because python is Cross-Platform
6) NumPy Library, We will not use this library but This will Installed with OpenCV-Python

Files for Downloading:

1) Haarcascade for Mask Trained by Me, Click Here
2) Haarcascade for Face come with OpenCV-Python by default. Click here for Download Manually

4) Main Program:

import cv2
import numpy as np
cam = cv2.VideoCapture(0)

obj = cv2.CascadeClassifier("myhaar.xml")
face = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")

while 1:
r,img = cam.read()
img = cv2.flip(img,3)
mask = obj.detectMultiScale(img,1.3,5)
faces = face.detectMultiScale(img,1.3,5)
for (x,y,w,h) in mask:
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
cv2.putText(img,"Very Good! Keep it Up",(50,50),cv2.FONT_HERSHEY_SIMPLEX,1,(0,255,0),3,cv2.LINE_AA)
if len(mask) == 0:
print("Mask Not Found! Be Safe from CORONA.")
for (x1,y1,w1,h1) in faces:
cv2.rectangle(img,(x1,y1),(x1+w1,y1+h1),(0,0,255),2)
cv2.putText(img,"Be Safe! Mask Not Found.",(50,50),cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,255),3,cv2.LINE_AA)
cv2.imshow("A",img)
if cv2.waitKey(1) == ord('q'):
break
cv2.destroyAllWindows()


Tutorial:






how to implement YOLOv3 using Python and TensorFlow

Object Detection with YOLOv3 Introduction YOLOv3 (You Only Look Once version 3) is a real-time object detection algorithm that can detect ob...