10 lines of Python code to achieve AI target detection technology [recommended]

Time:2020-2-23

With only 10 lines of Python code, we can achieve target detection in computer vision.


from imageai.Detection import ObjectDetection
import os

execution_path = os.getcwd()

detector = ObjectDetection()
detector.setModelTypeAsRetinaNet()
detector.setModelPath( os.path.join(execution_path , "resnet50_coco_best_v2.0.1.h5"))
detector.loadModel()
detections = detector.detectObjectsFromImage(input_image=os.path.join(execution_path , "image.jpg"), output_image_path=os.path.join(execution_path , "imagenew.jpg"))

for eachObject in detections:
print(eachObject["name"] + " : " + eachObject["percentage_probability"] )

Yes, with only 10 lines of code, we can achieve the target detection technology widely used in current AI products.

After reading the code, let’s talk about the technical background behind the target detection, and interpret the origin and implementation principle of these 10 lines of Python code.

Introduction to target detection

An important field of artificial intelligence is computer vision, which refers to the science of computer and software system to recognize and understand images and videos. Computer vision includes many subdivision directions, such as image recognition, target detection, image generation and image super-resolution. Among them, target detection has the most profound significance in the field of computer vision because of its wide use.

Target detection refers to the ability of computer and software system to locate and recognize objects in image / picture. Target detection technology has been widely used in face detection, vehicle detection, traffic statistics, network images, security systems and unmanned vehicles and other fields. Like other computer vision technologies, target detection will become an important part of artificial intelligence in the future, which has a broad development prospect.

However, using modern target detection methods in software applications and systems and creating applications based on these methods are not simple and direct. In the early stage of target detection, some classical algorithms are used, such as those supported in OpenCV. However, the performance of these algorithms is not stable, and there are great differences in different situations.

In 2012, the breakthrough of deep learning technology gave birth to a large number of highly accurate target detection algorithms, such as r-cnn, fast RCNN, fast RCNN, retinaet and fast and accurate SSD and Yolo. Using these deep learning based methods and algorithms requires understanding a large number of mathematical and deep learning frameworks. Now there are millions of developers around the world using target detection technology to create new products and new projects, but due to the complexity of understanding and using, many people still have no idea.

In order to solve this problem, computer vision expert Moses olafenwa led the team to launch the python library imageai, which enables developers to easily apply the most advanced computer vision technology to their own projects and products with only a few lines of code.

The 10 line code implementation shown at the beginning is to use imageai.

How to achieve target detection easily with imageai

Using imageai to perform target detection, you only need the following 4 steps:

1. Install Python on the computer

2. Install imageai and its environment dependence

3. Download the target detection module file

4. Run the sample code, which is the 10 lines we show

Let’s go through it step by step.

1) Download and install Python 3 from the python official website

python.org/

2) Install the following environment dependencies through pip

1.Tensorflow

pip install tensorflow

2.Numpy

pip install numpy

3.SciPy

pip install scipy

4.OpenCV

pip install opencv-python

5.Pillow

pip install pillow

6.Matplotlib

pip install matplotlib

7.H5py

pip install h5py

8.Keras

pip install keras

9.ImageAI

pip install

3) Use this link to download the retinaet model file for target detection.

Now that we have installed all the dependencies, we are ready to write our first target detection code. Create a python file, name it (for example, firstdetection. Py), write the following code to the file, and then copy the retinaet model file and the image you want to detect to the folder containing the python file.

FirstDetection.py


from imageai.Detection import ObjectDetection
import os

execution_path = os.getcwd()

detector = ObjectDetection()
detector.setModelTypeAsRetinaNet()
detector.setModelPath( os.path.join(execution_path , "resnet50_coco_best_v2.0.1.h5"))
detector.loadModel()
detections = detector.detectObjectsFromImage(input_image=os.path.join(execution_path , "image.jpg"), output_image_path=os.path.join(execution_path , "imagenew.jpg"))
for eachObject in detections:
print(eachObject["name"] + " : " + eachObject["percentage_probability"] )

Then run the code and wait for the console to print the results. After the console prints the result, it can be openedFirstDetection.pyIn the folder, you will find that there are new images saved in it. For example, the following two example images and two new images saved after target detection.

Before target detection:

After target detection:

We can see the name and probability of the detected object on the image.

Read 10 lines of code

Let’s explain how these 10 lines of code work.


from imageai.Detection import ObjectDetection
import os
execution_path = os.getcwd()

In the above three lines of code, we import the imageai target detection class in the first line, the python OS class in the second line, and a variable in the third line to obtain the path to the folder where our Python file, retinaet model file and image are located.


detector = ObjectDetection()
detector.setModelTypeAsRetinaNet()
detector.setModelPath( os.path.join(execution_path , "resnet50_coco_best_v2.0.1.h5"))
detector.loadModel()
detections = detector.detectObjectsFromImage(input_image=os.path.join(execution_path , "image.jpg"), output_image_path=os.path.join(execution_path , "imagenew.jpg"))

In the above 5 lines of code, we define our target detection class in the first line, set the model type of retinanet in the second line, set the model path to the path of retinanet model in the third line, load the model into the target detection class in the fourth line, and then call the detection function in the fifth line, and analyze in the input and output image path.


for eachObject in detections:
print(eachObject["name"] + " : " + eachObject["percentage_probability"] )

In the two lines above, we iterate over the first linedetector.detectObjectFromImageAll the results returned by the function, and then print out the detection results (name and probability) of each object on the image by the model in the second line.

Imageai supports many powerful target detection customization functions, one of which is to extract the image of each object detected on the image. Just add the additional parametersextract_detected_objects=TrueResolve to the detectobjectsfromimage function, as shown below, the target detection class will create a folder for image objects, extract each image, save them in the newly created folder, and return an additional array containing the path through each image.


detections, extracted_images = detector.detectObjectsFromImage(input_image=os.path.join(execution_path , "image.jpg"), output_image_path=os.path.join(execution_path , "imagenew.jpg"), extract_detected_objects=True)

Using the first image as an example, we can get individual images of each object detected in the image:

Imageai provides many functions, which can be used for customization and production deployment of various target detection tasks. Include:

-Adjust the minimum probability: objects with a default probability of less than 50% will not be displayed. You can adjust this number if necessary.

-Custom target detection: using the customobject class provided, you can detect one or more specific objects.

-Adjust the detection speed: you can adjust the detection speed by setting the detection speed to “fast”, “faster” and “fastest”.

-I / O type: you can customize the path of image, numpy array or image file stream for I / O.

Indeed, it is not amazing to see every line of these 10 lines of code, but also with many libraries. But using only 10 lines of code can make it easy to achieve the very troublesome target detection before, or we can talk about awesome two words.

summary

The above is the 10 lines of Python code introduced by Xiaobian to achieve AI target detection technology, hoping to help you. If you have any questions, please leave a message to me, and Xiaobian will reply to you in time. Thank you very much for your support of the developepaer website! If you think this article is helpful to you, welcome to reprint, please indicate the source, thank you!