tf.expand_dims()

Function Definition: tf.expand_dims(input, axis, name)

Description

The function returns a tensor with a length 1 axis inserted at the index axis.

Given a tensor input, this operation inserts a dimension of length 1 at the dimension index axis of input‘s shape. The dimension index follows Python indexing rules: It’s zero-based, a negative index is counted backward from the end.

This operation is useful to:

  • Add an outer “batch” dimension to a single element.
  • Align axes for broadcasting.
  • To add an inner vector length axis to a tensor of scalars.

Import Libraries

####################imports####################
#do not change

import cv2
import numpy as np
import tensorflow as tf

#do not change
####################imports####################

Parameters

NameTypeDescriptionExpected ValuesDefault Value
inputstringA tensorTensor
axisintInteger specifying the dimension index at which to expand the shape of input. Given an input of D dimensions, axis must be in range [-(D+1), D] (inclusive).Integer
namestringOptional string. The name of the output Tensor.String

Example

The project detects the number of faces detected on the stage.

Code

sprite = Sprite('Tobi')

fd = FaceDetection()

# Enable Bounding Box on the stage
fd.enablebox()

# Set Theshold of the stage
fd.setthreshold(0.9)

fd.analysestage()

sprite.say(str(fd.count()) + " Faces Detected")

Output

The example demonstrates how face recognition works with analysis on the stage.

The example demonstrates the application of face recognition with stage. Following are the key steps happening:

  1. Initializing the program with parameters for the sprite and face detection library.
  2. Saving Chris's face as class 1.
  3. Saving Robert's face as class 2.
  4. Running face recognition and placing the square box sprite on the faces of Chris and Robert.

Code

sprite = Sprite('Square Box')
fd = FaceDetection()
import time

fd.setthreshold(0.5)
fd.enablebox()

# Reset Database
fd.deleteallclass()

# Adding Chirs face to database
sprite.switchbackdrop("Chris")
time.sleep(0.5)
fd.addclassfromstage(1, "Chris")

# Adding Robert face to database
sprite.switchbackdrop("Robert")
time.sleep(0.5)
fd.addclassfromstage(2, "Robert")

sprite.switchbackdrop("Robert and Chris")

while True:
  fd.recognisefromstage()
  
  print(fd.count())
  for i in range(fd.count()):
    sprite.setx(fd.x(i+1))
    sprite.sety(fd.y(i+1))
    sprite.setsize(fd.width(i+1))
    sprite.say(getclassname(i+1))
    time.sleep(1)

Result

The example demonstrates how face recognition works with analysis on the camera.

The example demonstrates the application of face recognition with camera feed. Following are the key steps happening:

  1. Initializing the program with parameters for the sprite and face detection library.
  2. Saving the face showing in the camera as class 1.
  3. Running face recognition and reporting whether class 1 is detected or not.

Code

sprite = Sprite('Tobi')

fd = FaceDetection()
import time

fd.setthreshold(0.5)
fd.video("on", 0)
fd.enablebox()
time.sleep(2)

fd.deleteallclass()

# Adding face 1 to database
fd.addclassfromstage(1, "Face 1")

while True:
  fd.recognisefromcamera()
  
  if fd.isclassdetected(1):
    sprite.say("Face 1 Recognised")
  else:
    sprite.say("Face 1 Missing")

Output

The example demonstrates the application of face detection with a stage feed.

The example demonstrates the application of face detection with a stage feed. Following are the key steps happening:

  1. Initializing the program with parameters for the sprite and face detection library.
  2. Running face detection
  3. Running the loop to show every face and its expression

Code

sprite = Sprite('Square Box')
import time
fd = FaceDetection()

# Disable Bounding Box on the stage
fd.disablebox()

# Set Theshold of the stage
fd.setthreshold(0.4)

fd.analysestage()

print(fd.count())

for i in range(fd.count()):
  sprite.setx(fd.x(i + 1))
  sprite.sety(fd.y(i + 1))
  sprite.setsize(fd.width(i + 1))
  sprite.say("Face " + str(i + 1) + ": " + fd.expression(i + 1))
  time.sleep(1)

Output

 

The example demonstrates how to use face landmarks in the projects.

The example demonstrates how to use face landmarks in the projects. Following are the key steps happening:

  1. Initializing the program with parameters for the sprite, pen, and face detection library.
  2. Running face detection.
  3. Running the loop to show every landmark on the face.

Code

sprite = Sprite('Ball')
fd = FaceDetection()
import time
pen = Pen()

pen.clear()
sprite.setsize(10)

fd.enablebox()

fd.analysestage()

for i in range(68):
  sprite.setx(fd.landmarksx(1, i+1))
  sprite.sety(fd.landmarksy(1, i+1))
  pen.stamp()
  time.sleep(0.2)

Output

 

The example demonstrates how to use face detection with a camera feed.

The example demonstrates how to use face detection with a camera feed. Following are the key steps happening:

  1. Initializing the program with parameters for the sprite, and face detection library.
  2. Running face detection.
  3. Running the loop to show every face and expression.

Code

sprite = Sprite('Square Box')
import time
fd = FaceDetection()

fd.video("on", 0)

# Enable Bounding Box on the stage
fd.enablebox()

# Set Theshold of the stage
fd.setthreshold(0.5)

while True:
  fd.analysestage()

  for i in range(fd.count()):
    sprite.setx(fd.x(i + 1))
    sprite.sety(fd.y(i + 1))
    sprite.setsize(fd.width(i + 1))
    sprite.say(fd.expression(i + 1))

Output

Beating-Heart (4)
The project shows how to create custom patterns on Quarky RGB LED in Stage Mode.

Beating-Heart (4)

Code

sprite = Sprite('Tobi')
quarky = Quarky()

import time

while True:
	quarky.drawpattern("jjbjbjjjbbbbbjjbbbbbjjjbbbjjjjjbjjj")
	time.sleep(0.4)
	quarky.drawpattern("jjjjjjjjjbjbjjjjbbbjjjjjbjjjjjjjjjj")
	time.sleep(0.4)
The project shows how to create custom patterns on Quarky RGB LED in Upload Mode.

Beating-Heart (4)

Code

from quarky import *
import time

while True:
	quarky.drawpattern("jjbjbjjjbbbbbjjbbbbbjjjbbbjjjjjbjjj")
	time.sleep(1)
	quarky.drawpattern("jjjjjjjjjbjbjjjjbbbjjjjjbjjjjjjjjjj")
	time.sleep(1)
The project shows how to create custom patterns on Quarky RGB LED in Upload Mode.

Beating-Heart (4)

Script

Python Code Generated

# This python code is generated by PictoBlox

from quarky import *
# This python code is generated by PictoBlox

# imported modules
import time



while True:
	quarky.drawpattern("jjbjbjjjbbbbbjjbbbbbjjjbbbjjjjjbjjj")
	time.sleep(1)
	quarky.drawpattern("jjjjjjjjjbjbjjjjbbbjjjjjbjjjjjjjjjj")
	time.sleep(1)
	
	
Beating-Heart
The project shows how to create custom patterns on Quarky RGB LED in Upload Mode.

Beating-Heart (4)

Script

The project makes the Quarky display the expression according to the expression identified from the Face Recognition.

Script

The example shows how to run image classification in Python on a webcam feed using OpenCV.

Image Classification Model

Code

####################imports####################
#do not change

import cv2
import numpy as np
import tensorflow as tf

sprite = Sprite("Tobi")

#do not change
####################imports####################

#Following are the model and video capture configurations
#do not change

model = tf.keras.models.load_model('saved_model.h5',
                                   custom_objects=None,
                                   compile=True,
                                   options=None)

cap = cv2.VideoCapture(0)  # Using device's camera to capture video
text_color = (206, 235, 135)
org = (50, 50)
font = cv2.FONT_HERSHEY_SIMPLEX
fontScale = 1
thickness = 3

class_list = ['Mask Off', 'Mask On', 'Mask Wrong']  # List of all the classes

#do not change
###############################################


def checkmask(predicted_class):
  if predicted_class == 'Mask On':
    sprite.say("Thank you for wearing the mask")
  elif predicted_class == 'Mask Off':
    sprite.say("Please wear a mask")
  else:
    sprite.say("Please wear the mask propertly")


#This is the while loop block, computations happen here

while True:
  ret, image_np = cap.read()  # Reading the captured images
  image_np = cv2.flip(image_np, 1)
  image_resized = cv2.resize(image_np, (224, 224))
  img_array = tf.expand_dims(image_resized,
                             0)  # Expanding the image array dimensions
  predict = model.predict(img_array)  # Making an initial model prediction
  predict_index = np.argmax(predict[0],
                            axis=0)  # Generating index out of the prediction
  predicted_class = class_list[
      predict_index]  # Tallying the index with class list

  image_np = cv2.putText(
      image_np, "Image Classification Output: " + str(predicted_class), org,
      font, fontScale, text_color, thickness, cv2.LINE_AA)

  print(predict)
  cv2.imshow("Image Classification Window",
             image_np)  # Displaying the classification window
  checkmask(predicted_class)

  if cv2.waitKey(25) & 0xFF == ord(
      'q'):  # Press 'q' to close the classification window
    break

cap.release()  # Stops taking video input
cv2.destroyAllWindows()  #Closes input window
The example shows how to run image classification in Python on an image file using OpenCV.

Image Classification Model

 

Code

####################imports####################
#do not change

import cv2
import numpy as np
import tensorflow as tf

#do not change
####################imports####################

#Following are the model and video capture configurations
#do not change

model = tf.keras.models.load_model('saved_model.h5',
                                   custom_objects=None,
                                   compile=True,
                                   options=None)

text_color = (206, 235, 135)
org = (50, 50)
font = cv2.FONT_HERSHEY_SIMPLEX
fontScale = 0.5
thickness = 1

class_list = ['Bacteria', 'Normal', 'Virus']  # List of all the classes

#do not change
###############################################

image_np = cv2.imread("test.jpg", cv2.IMREAD_COLOR)
image_resized = cv2.resize(image_np, (224, 224))
img_array = tf.expand_dims(image_resized,
                           0)  # Expanding the image array dimensions
predict = model.predict(img_array)  # Making an initial model prediction
predict_index = np.argmax(predict[0],
                          axis=0)  # Generating index out of the prediction
predicted_class = class_list[
    predict_index]  # Tallying the index with class list

image_np = cv2.putText(image_np,
                       "Image Classification Output: " + str(predicted_class),
                       org, font, fontScale, text_color, thickness,
                       cv2.LINE_AA)

print(predict)
cv2.imshow("Image Classification Window",
           image_np)  # Displaying the classification window

cv2.imwrite("TestResult.jpg", image_np)
cv2.waitKey(0)
cv2.destroyAllWindows()
The example shows how to run image classification in Block Coding.

Script

The example demonstrates how to use the confidence threshold in face detection (Block Coding).

Script

Output

The example displays how to detect expression using face detection and mimic the expression on Quarky. The expression is detected by the camera.

Script

Output

The example shows how to create a face filter with Face Detection. It also includes how to make the filter tilt with face angles.

Script

Exmaple

Face Landmarks
The example demonstrates how to use face landmarks in the projects.

The example demonstrates how to use face landmarks in the projects. Following are the key steps happening:

  1. Initializing the program with parameters for the sprite, pen, and face detection library.
  2. Running face detection.
  3. Running the loop to show every landmark on the face.

Script

Output

Face Landmarks

The example demonstrates how face recognition works with analysis on the camera.

The example demonstrates the application of face recognition with a camera feed. Following are the key steps happening:

  1. Initializing the program with parameters for the sprite and face detection library.
  2. Saving the face showing in the camera as class 1.
  3. Running face recognition and reporting whether class 1 is detected or not.

Script

Output

The example demonstrates how face recognition works with analysis on the stage.

The example demonstrates the application of face recognition with stage. Following are the key steps happening:

  1. Initializing the program with parameters for the sprite and face detection library.
  2. Saving Chris’s face as class 1.
  3. Saving Robert’s face as class 2.
  4. Running face recognition and placing the square box sprite on the faces of Chris and Robert.

Script

Output

The example demonstrates the use of clone and gliding function in Sprite. 

The example demonstrates the use of clone and gliding function in Sprite:

  1. Whenever the sprite is clicked, a clone is created.
  2. When a clone is created its position is set to a random position on the top of the stage and then it glides down to the bottom.
  3. When it reaches the bottom, the clone is deleted.

Script

Output

The example demonstrates how to make the sprite glide to a random position on the stage when it is clicked.

Script

Output

The example demonstrates how to use stamping and the mouse location sensing in Block coding.

Script

Output

The example demonstrates how to use keys sensing to control the movement of the sprite.

Script

Output

The example demonstrates the wall bouncing of the sprite and rotation style.

Script

 

Output

The example demonstrates how to make the sprite follow the mouse.

Script

Output

The example demonstrates how to add gravity into the project on a bouncing ball.

Script

  1. Main Script to change the speed and position parameters of the ball.
  2. Custom function to initialize the ball position and speed with random variables.
  3. Custom function to check the boundary conditions and set the rules.

Output

The example demonstrates how to implement mouse tracking.

Script

Output

The example demonstrates how to add movement to a sprite using the key detection hat block.

Script

Output

The example demonstrates the sprite direction in PictoBlox.

Script

Output

All articles loaded
No more articles to load
Table of Contents
[PythonExtension]

Get in Touch!