Silicon's blog

Menu
  • Home
  • Kadena
  • Solana
  • Ethereum
  • Bot Automation
  • Proxmox
  • Nginx Proxy Manager
  • Others
  • Contact
Menu

Install openvino (CPU only) on a fresh ubuntu 22.04

Posted on January 10, 2023May 17, 2023 by Silicon
Sharing is Caring:
Twitter 0
Copy 0

 

The python version is 3.10.6 by default on ubuntu 22.04. It may have some compatibility issues with OpenVINO. In this article, I will demonstrate how to install Openvino (CPU only) on a fresh ubuntu 22.04. The CPU model I used in this demonstration is the Intel i5-8250u.

Step 1: Add this repository to your ubuntu system


sudo add-apt-repository ppa:deadsnakes/ppa 

Step 2: Update the list of available packages and install python 3.9


sudo apt update
sudo apt install python3.9-dev -y
sudo apt install python3.9-venv -y 
sudo apt install python3-pip -y

Step 3: Create a virtual environment for OpenVINO


cd ~
python3.9 -m venv openvino_env

Step 4: Activate the virtual environment and install the required packages using pip


source ~/openvino_env/bin/activate
python3.9 -m pip install --upgrade pip
python3.9 -m pip install openvino-dev[tensorflow2,pytorch,caffe]

Step 5: Install git and clone the MobileNet-SSD project from GitHub for testing


cd ~
git clone https://github.com/chuanqi305/MobileNet-SSD.git

Step 6: Move to the MobileNet-SSD folder and create a script for testing. The script I used is based on an article written by Adrian Rosebrock on Pyimagesearch in 2019. I made some modifications to it. 


cd MobileNet-SSD
sudo nano detection_image.py

# import the necessary packages
import numpy as np
import argparse
import time
import cv2

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-p", "--prototxt", required=True,
	help="path to Caffe 'deploy' prototxt file")
ap.add_argument("-m", "--model", required=True,
	help="path to Caffe pre-trained model")
ap.add_argument("-c", "--confidence", type=float, default=0.2,
	help="minimum probability to filter weak detections")
ap.add_argument("-u", "--movidius", type=bool, default=0,
	help="boolean indicating if the Movidius should be used")
args = vars(ap.parse_args())
# initialize the list of class labels MobileNet SSD was trained to
# detect, then generate a set of bounding box colors for each class
CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat",
	"bottle", "bus", "car", "cat", "chair", "cow", "diningtable",
	"dog", "horse", "motorbike", "person", "pottedplant", "sheep",
	"sofa", "train", "tvmonitor"]
COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))
# load our serialized model from disk
print("[INFO] loading model...")
net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"])

#CPU only
net.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU)

image_path = "./images/000001.jpg"
frame = cv2.imread(image_path)

time.sleep(2.0)

# grab the frame dimensions and convert it to a blob with a maximum width of 300 pixels and a maximum height of 300 pixels
h, w, _ = frame.shape
frame = cv2.resize(frame, (0,0), fx=300/w, fy=300/h)

blob = cv2.dnn.blobFromImage(frame, 0.007843, (300, 300), 127.5)
# pass the blob through the network and obtain the detections and
# predictions
net.setInput(blob)
detections = net.forward()
# loop over the detections
for i in np.arange(0, detections.shape[2]):
	# extract the confidence (i.e., probability) associated with
	# the prediction
	confidence = detections[0, 0, i, 2]
	# filter out weak detections by ensuring the `confidence` is
	# greater than the minimum confidence
	if confidence > args["confidence"]:
		# extract the index of the class label from the
		# `detections`, then compute the (x, y)-coordinates of
		# the bounding box for the object
		idx = int(detections[0, 0, i, 1])
		box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
		(startX, startY, endX, endY) = box.astype("int")
		# draw the prediction on the frame
		label = "{}: {:.2f}%".format(CLASSES[idx],
			confidence * 100)
		cv2.rectangle(frame, (startX, startY), (endX, endY),
			COLORS[idx], 2)
		y = startY - 15 if startY - 15 > 15 else startY + 15
		cv2.putText(frame, label, (startX, y),
			cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLORS[idx], 2)
# show the output frame
cv2.imshow("Frame", frame)

#halt the program for 5s before exit
key = cv2.waitKey(5000)

# do a bit of cleanup
cv2.destroyAllWindows()

Press ctrl + X to save the file Step 8: Test the program with this command


python3.9 detection_image.py --prototxt deploy.prototxt --model mobilenet_iter_73000.caffemodel

Optional: Try this code to use the Caffe module with a web camera or video. It is based on an article by Adrian Rosebrock on Pyimagesearch in 2019, and I modified it. It is not perfect, as the video path is hard-coded; you may change the program by yourself to use a dynamic path.


sudo nano detection.py

# import the necessary packages
import numpy as np
import argparse
import time
import cv2

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-p", "--prototxt", required=True,
	help="path to Caffe 'deploy' prototxt file")
ap.add_argument("-m", "--model", required=True,
	help="path to Caffe pre-trained model")
ap.add_argument("-c", "--confidence", type=float, default=0.2,
	help="minimum probability to filter weak detections")
ap.add_argument("-u", "--movidius", type=bool, default=0,
	help="boolean indicating if the Movidius should be used")
args = vars(ap.parse_args())
# initialize the list of class labels MobileNet SSD was trained to
# detect, then generate a set of bounding box colors for each class
CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat",
	"bottle", "bus", "car", "cat", "chair", "cow", "diningtable",
	"dog", "horse", "motorbike", "person", "pottedplant", "sheep",
	"sofa", "train", "tvmonitor"]
COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))
# load our serialized model from disk
print("[INFO] loading model...")
net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"])

#CPU only
net.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU)
# initialize the video stream, allow the cammera sensor to warmup
print("[INFO] starting video stream...")
#change this to your web camera streaming path
url = "rtsp://192.168.1.202:554/"
vs = cv2.VideoCapture(url)

#for video
#video_path = "./your_video_path.avi"
#vs = cv2.VideoCapture(video_path)

time.sleep(2.0)
# loop over the frames from the video stream
while True:
	# grab the frame from the threaded video stream and resize it
	# to have a maximum width of 300 pixels and a maximum height of 300 pixels
	ret, frame = vs.read()
	# grab the frame dimensions and convert it to a blob
	h, w, _ = frame.shape
	frame = cv2.resize(frame, (0,0), fx=300/w, fy=300/h)
	blob = cv2.dnn.blobFromImage(frame, 0.007843, (300, 300), 127.5)
	# pass the blob through the network and obtain the detections and
	# predictions
	net.setInput(blob)
	detections = net.forward()
	# loop over the detections
	for i in np.arange(0, detections.shape[2]):
		# extract the confidence (i.e., probability) associated with
		# the prediction
		confidence = detections[0, 0, i, 2]
		# filter out weak detections by ensuring the `confidence` is
		# greater than the minimum confidence
		if confidence > args["confidence"]:
			# extract the index of the class label from the
			# `detections`, then compute the (x, y)-coordinates of
			# the bounding box for the object
			idx = int(detections[0, 0, i, 1])
			box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
			(startX, startY, endX, endY) = box.astype("int")
			# draw the prediction on the frame
			label = "{}: {:.2f}%".format(CLASSES[idx],
				confidence * 100)
			cv2.rectangle(frame, (startX, startY), (endX, endY),
				COLORS[idx], 2)
			y = startY - 15 if startY - 15 > 15 else startY + 15
			cv2.putText(frame, label, (startX, y),
				cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLORS[idx], 2)
	# show the output frame
	cv2.imshow("Frame", frame)
	key = cv2.waitKey(1) & 0xFF
	# if the `q` key was pressed, break from the loop
	if key == ord("q"):
		break

# do a bit of cleanup
cv2.destroyAllWindows()
vs.stop()

Press ctrl + X to save the file Test the program with this command


python3.9 detection.py --prototxt deploy.prototxt --model mobilenet_iter_73000.caffemodel

Congratulation if your OpenVINO works appropriately with the Caffe module. I have not tested other modules yet, such as PyTorch and TensorFlow2. You may try to use these modules by yourself.

Leave a comment below if you have any trouble. I am willing to help you if I have time.

Leave a Reply Cancel reply


The reCAPTCHA verification period has expired. Please reload the page.

©2025 Silicon's blog
Click to Copy