使用Java調(diào)用Yolo模型的基本步驟
一、Yolo模型簡(jiǎn)介
Yolo(You Only Look Once)是一種基于深度學(xué)習(xí)的目標(biāo)檢測(cè)算法,它可以在一張圖像中同時(shí)檢測(cè)出多個(gè)目標(biāo),并給出它們的位置和類(lèi)別。相比于傳統(tǒng)的目標(biāo)檢測(cè)算法,Yolo算法具有檢測(cè)速度快、精度高等優(yōu)點(diǎn),因此在實(shí)際應(yīng)用中得到了廣泛的應(yīng)用。
二、Java調(diào)用Yolo模型的方法
在Java中調(diào)用Yolo模型,需要使用OpenCV庫(kù)。OpenCV是一個(gè)開(kāi)源的計(jì)算機(jī)視覺(jué)庫(kù),它提供了各種各樣的圖像處理和計(jì)算機(jī)視覺(jué)算法,包括圖像處理、特征提取、目標(biāo)檢測(cè)等。
下面我們將介紹如何使用Java調(diào)用Yolo模型。
1. 安裝OpenCV
首先,我們需要安裝OpenCV庫(kù)??梢詮腛penCV官網(wǎng)(https://opencv.org/)下載OpenCV的安裝包,然后按照官方文檔進(jìn)行安裝。
2. 下載Yolo模型文件
接下來(lái),我們需要下載Yolo模型文件??梢詮腨olo官網(wǎng)(https://pjreddie.com/darknet/yolo/)下載預(yù)訓(xùn)練的Yolo模型文件,包括權(quán)重文件和配置文件。這些文件將用于檢測(cè)圖像中的目標(biāo)。
下面是從Yolo官網(wǎng)下載預(yù)訓(xùn)練模型文件的詳細(xì)步驟:
1. 打開(kāi)Yolo官網(wǎng)(https://pjreddie.com/darknet/yolo/)。
2. 點(diǎn)擊頁(yè)面上方的“Download”按鈕。
3. 在下載頁(yè)面中,找到“Pre-trained Models”部分。
4. 在“Pre-trained Models”部分中,選擇你需要下載的模型文件。例如,如果你需要下載YOLOv3模型文件,可以點(diǎn)擊“YOLOv3”鏈接。
5. 在YOLOv3模型文件下載頁(yè)面中,你會(huì)看到兩個(gè)鏈接:一個(gè)是“yolov3.weights”,另一個(gè)是“yolov3-tiny.weights”。這兩個(gè)鏈接分別對(duì)應(yīng)YOLOv3和YOLOv3-tiny模型文件。
6. 點(diǎn)擊你需要下載的模型文件鏈接,瀏覽器會(huì)自動(dòng)開(kāi)始下載。
7. 下載完成后,你可以將模型文件保存在你的本地計(jì)算機(jī)上,以備后續(xù)使用。
注意事項(xiàng):
1. 下載模型文件可能需要一定的時(shí)間,具體時(shí)間取決于你的網(wǎng)絡(luò)速度和文件大小。
2. 下載的模型文件是二進(jìn)制文件,不能直接查看或編輯。如果需要使用模型文件,你需要使用相應(yīng)的深度學(xué)習(xí)框架(如TensorFlow、PyTorch等)加載模型文件,并進(jìn)行預(yù)測(cè)或訓(xùn)練等操作。
3. YOLOv3和YOLOv3-tiny模型文件的區(qū)別在于模型大小和精度。YOLOv3模型文件更大,但精度更高;YOLOv3-tiny模型文件更小,但精度較低。根據(jù)你的需求選擇合適的模型文件。
3. 編寫(xiě)Java代碼
在安裝好OpenCV庫(kù)和下載好Yolo模型文件之后,我們就可以開(kāi)始編寫(xiě)Java代碼了。
首先,我們需要加載Yolo模型文件??梢允褂肙penCV提供的Dnn模塊來(lái)加載模型文件。具體代碼如下:
String modelConfiguration = "path/to/yolov3.cfg"; String modelWeights = "path/to/yolov3.weights"; Net net = Dnn.readNetFromDarknet(modelConfiguration, modelWeights);
其中,modelConfiguration是Yolo模型的配置文件路徑,modelWeights是Yolo模型的權(quán)重文件路徑。Net是OpenCV中的一個(gè)類(lèi),它表示一個(gè)神經(jīng)網(wǎng)絡(luò)模型。
接下來(lái),我們需要讀取圖像并進(jìn)行目標(biāo)檢測(cè)。可以使用OpenCV提供的Imgcodecs模塊來(lái)讀取圖像,使用Dnn模塊來(lái)進(jìn)行目標(biāo)檢測(cè)。具體代碼如下:
String imagePath = "path/to/image.jpg"; Mat image = Imgcodecs.imread(imagePath); Mat blob = Dnn.blobFromImage(image, 1/255.0, new Size(416, 416), new Scalar(0,0,0), true, false); net.setInput(blob); List<Mat> outputs = new ArrayList<>(); List<String> outNames = net.getUnconnectedOutLayersNames(); net.forward(outputs, outNames);
其中,imagePath是待檢測(cè)的圖像路徑,image是讀取的圖像。blobFromImage方法將圖像轉(zhuǎn)換為神經(jīng)網(wǎng)絡(luò)的輸入格式。Size表示輸入圖像的大小,Scalar表示輸入圖像的均值。net.setInput方法將輸入數(shù)據(jù)設(shè)置為神經(jīng)網(wǎng)絡(luò)的輸入。getUnconnectedOutLayersNames方法獲取神經(jīng)網(wǎng)絡(luò)的輸出層名稱(chēng)。forward方法將輸入數(shù)據(jù)傳遞給神經(jīng)網(wǎng)絡(luò),并獲取輸出結(jié)果。
最后,我們需要解析輸出結(jié)果并繪制檢測(cè)框。具體代碼如下:
float confThreshold = 0.5f; List<Integer> classIds = new ArrayList<>(); List<Float> confidences = new ArrayList<>(); List<Rect> boxes = new ArrayList<>(); for (int i = 0; i < outputs.size(); ++i) { Mat output = outputs.get(i); for (int j = 0; j < output.rows(); ++j) { Mat row = output.row(j); Mat scores = row.colRange(5, output.cols()); Core.MinMaxLocResult mm = Core.minMaxLoc(scores); float confidence = (float) mm.maxVal; Point classIdPoint = mm.maxLoc; if (confidence > confThreshold) { int centerX = (int) (row.get(0, 0)[0] * image.cols()); int centerY = (int) (row.get(0, 1)[0] * image.rows()); int width = (int) (row.get(0, 2)[0] * image.cols()); int height = (int) (row.get(0, 3)[0] * image.rows()); int left = centerX - width / 2; int top = centerY - height / 2; classIds.add((int) classIdPoint.x); confidences.add(confidence); boxes.add(new Rect(left, top, width, height)); } } } Mat labels = new Mat(); MatOfFloat confidencesMat = new MatOfFloat(Converters.vector_float_to_Mat(confidences)); MatOfInt indices = new MatOfInt(); Dnn.NMSBoxes(boxes, confidencesMat, confThreshold, 0.4f, indices); for (int i = 0; i < indices.total(); ++i) { int idx = (int) indices.get(i, 0)[0]; Rect box = boxes.get(idx); Imgproc.rectangle(image, box.tl(), box.br(), new Scalar(0, 255, 0), 2); }
其中,confThreshold是置信度閾值,classIds表示檢測(cè)到的目標(biāo)類(lèi)別,confidences表示檢測(cè)到的目標(biāo)置信度,boxes表示檢測(cè)到的目標(biāo)框。MinMaxLocResult表示最大值和最小值的位置和值。NMSBoxes方法對(duì)檢測(cè)框進(jìn)行非極大值抑制,去除重疊的框。
我們可以將檢測(cè)結(jié)果保存到文件或顯示在屏幕上。具體代碼如下:
String outputImagePath = "path/to/output/image.jpg"; Imgcodecs.imwrite(outputImagePath, image);
三、Yolo模型的應(yīng)用場(chǎng)景
Yolo模型是一種高效的目標(biāo)檢測(cè)算法,因此在許多領(lǐng)域都有廣泛的應(yīng)用。以下是一些常見(jiàn)的應(yīng)用場(chǎng)景:
1. 自動(dòng)駕駛
自動(dòng)駕駛是Yolo模型的一個(gè)重要應(yīng)用場(chǎng)景。通過(guò)使用Yolo模型,自動(dòng)駕駛汽車(chē)可以實(shí)時(shí)檢測(cè)道路上的車(chē)輛、行人、交通標(biāo)志等物體,從而更好地控制車(chē)輛的行駛。
2. 安防監(jiān)控
在安防監(jiān)控領(lǐng)域,Yolo模型可以用于實(shí)時(shí)檢測(cè)和跟蹤人員、車(chē)輛等物體,從而提高監(jiān)控系統(tǒng)的效率和準(zhǔn)確性。例如,在商場(chǎng)、銀行等公共場(chǎng)所,Yolo模型可以用于檢測(cè)和跟蹤可疑人員,從而提高安全性。
3. 醫(yī)療診斷
在醫(yī)療診斷領(lǐng)域,Yolo模型可以用于檢測(cè)和識(shí)別醫(yī)學(xué)圖像中的病變和異常,從而幫助醫(yī)生更準(zhǔn)確地診斷疾病。例如,在CT掃描和X光檢查中,Yolo模型可以用于檢測(cè)和識(shí)別腫瘤、結(jié)節(jié)等異常。
4. 工業(yè)生產(chǎn)
在工業(yè)生產(chǎn)領(lǐng)域,Yolo模型可以用于檢測(cè)和識(shí)別生產(chǎn)線上的物體,從而提高生產(chǎn)效率和質(zhì)量。例如,在電子工廠中,Yolo模型可以用于檢測(cè)和識(shí)別電子元器件,從而提高生產(chǎn)線的效率和準(zhǔn)確性。
四、總結(jié)
Yolo模型是一種高效的目標(biāo)檢測(cè)算法,具有快速、準(zhǔn)確、實(shí)時(shí)等優(yōu)點(diǎn)。通過(guò)使用Java調(diào)用Yolo模型,我們可以在Java應(yīng)用程序中實(shí)現(xiàn)目標(biāo)檢測(cè)功能,從而滿足各種應(yīng)用場(chǎng)景的需求。在未來(lái),隨著人工智能技術(shù)的不斷發(fā)展,Yolo模型將在更多領(lǐng)域得到廣泛應(yīng)用,為人們的生活和工作帶來(lái)更多的便利和效益。
五、示例代碼
以下是一個(gè)使用Java調(diào)用YOLO進(jìn)行目標(biāo)檢測(cè)的示例代碼:
import org.bytedeco.javacpp.Loader; import org.bytedeco.opencv.global.opencv_core; import org.bytedeco.opencv.opencv_core.*; import org.bytedeco.opencv.opencv_dnn.Net; import org.bytedeco.opencv.opencv_dnn.Net.LayerId; import org.bytedeco.opencv.opencv_dnn.Size; import org.bytedeco.opencv.opencv_imgcodecs.Imgcodecs; import org.bytedeco.opencv.opencv_imgproc.Imgproc; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; public class YoloDetector { private static final String MODEL_PATH = "yolov3.weights"; private static final String CONFIG_PATH = "yolov3.cfg"; private static final String[] CLASSES = {"person", "bicycle", "car", "motorbike", "aeroplane", "bus", "train", "truck", "boat", "traffic light", "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee", "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard", "tennis racket", "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "sofa", "pottedplant", "bed", "diningtable", "toilet", "tvmonitor", "laptop", "mouse", "remote", "keyboard", "cell phone", "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase", "scissors", "teddy bear", "hair drier", "toothbrush"}; public static void main(String[] args) { // Load the OpenCV and YOLO libraries Loader.load(org.bytedeco.opencv.global.opencv_core.class); Loader.load(org.bytedeco.opencv.global.opencv_imgproc.class); Loader.load(org.bytedeco.opencv.global.opencv_imgcodecs.class); Loader.load(org.bytedeco.opencv.global.opencv_dnn.class); // Load the YOLO model Net net = loadModel(); // Load the input image Mat image = Imgcodecs.imread("input.jpg"); // Perform object detection List<Mat> detections = detectObjects(net, image); // Draw bounding boxes around the detected objects drawBoundingBoxes(image, detections); // Save the output image Imgcodecs.imwrite("output.jpg", image); } private static Net loadModel() { // Load the model and configuration files File modelFile = new File(MODEL_PATH); File configFile = new File(CONFIG_PATH); // Create a new network from the model and configuration files Net net = new Net(); net.readFromDarknet(configFile.getAbsolutePath(), modelFile.getAbsolutePath()); // Set the backend and target to use OpenCV net.setPreferableBackend(org.bytedeco.opencv.global.opencv_dnn.DNN_BACKEND_OPENCV); net.setPreferableTarget(org.bytedeco.opencv.global.opencv_dnn.DNN_TARGET_CPU); return net; } private static List<Mat> detectObjects(Net net, Mat image) { // Create a blob from the input image Mat blob = org.bytedeco.opencv.global.opencv_dnn.blobFromImage(image, 1 / 255.0, new Size(416, 416), new Scalar(0, 0, 0), true, false); // Set the input to the network net.setInput(blob); // Get the output layers of the network List<LayerId> outLayers = new ArrayList<>(); outLayers.add(new LayerId(net.getLayerId("yolo_82"))); outLayers.add(new LayerId(net.getLayerId("yolo_94"))); outLayers.add(new LayerId(net.getLayerId("yolo_106"))); // Perform forward pass through the network List<Mat> detections = new ArrayList<>(); net.forward(detections, outLayers); return detections; } private static void drawBoundingBoxes(Mat image, List<Mat> detections) { // Loop over the detections for (Mat detection : detections) { // Loop over the rows of the detection for (int i = 0; i < detection.rows(); i++) { // Get the confidence and class ID of the detection float[] data = new float[5]; detection.get(i, 0, data); float confidence = data[4]; int classId = (int) data[1]; // Filter out weak detections if (confidence > 0.5) { // Get the bounding box coordinates int centerX = (int) (data[0] * image.cols()); int centerY = (int) (data[1] * image.rows()); int width = (int) (data[2] * image.cols()); int height = (int) (data[3] * image.rows()); int left = centerX - width / 2; int top = centerY - height / 2; // Draw the bounding box Rect rect = new Rect(left, top, width, height); Imgproc.rectangle(image, rect, new Scalar(0, 255, 0), 2); // Draw the class label String label = CLASSES[classId]; int[] baseLine = new int[1]; Size labelSize = Imgproc.getTextSize(label, Imgproc.FONT_HERSHEY_SIMPLEX, 0.5, 1, baseLine); Imgproc.rectangle(image, new Point(left, top - labelSize.height - 5), new Point(left + labelSize.width, top), new Scalar(0, 255, 0), -1); Imgproc.putText(image, label, new Point(left, top - 5), Imgproc.FONT_HERSHEY_SIMPLEX, 0.5, new Scalar(255, 255, 255), 1); } } } } }
這段代碼使用了OpenCV和YOLO,可以在本地讀取一張圖片,調(diào)用YOLO進(jìn)行目標(biāo)檢測(cè),并將檢測(cè)結(jié)果保存到本地。請(qǐng)注意,您需要下載YOLO的權(quán)重文件和配置文件,并將它們放在與代碼相同的目錄下。
七、DL4J
要使用Java調(diào)用yolo訓(xùn)練好的.pt模型,需要使用Java深度學(xué)習(xí)框架,如DL4J、Deeplearning4j等。這里以DL4J為例,介紹如何使用Java調(diào)用yolo訓(xùn)練好的.pt模型,并設(shè)計(jì)封裝成一個(gè)可執(zhí)行軟件.exe。
1. 下載yolo的.pt模型和對(duì)應(yīng)的配置文件,可以從yolo官網(wǎng)下載或者使用其他開(kāi)源項(xiàng)目提供的模型和配置文件。
2. 安裝DL4J,可以從DL4J官網(wǎng)下載或者使用Maven進(jìn)行安裝。
3. 使用DL4J加載yolo的.pt模型和配置文件,可以使用以下代碼:
Yolo2Model yoloModel = new Yolo2Model(); yoloModel.initTiny(); ComputationGraph computationGraph = (ComputationGraph) yoloModel.getModel();
4. 使用DL4J對(duì)圖像進(jìn)行預(yù)測(cè),可以使用以下代碼:
INDArray input = Nd4j.create(imageData); INDArray[] output = computationGraph.output(input);
其中,imageData是輸入圖像的數(shù)據(jù),output是輸出的預(yù)測(cè)結(jié)果。
5. 將預(yù)測(cè)結(jié)果進(jìn)行解析,可以使用以下代碼:
YoloUtils.getPredictedObjects(labels, output, 0.6, 0.4);
其中,labels是類(lèi)別標(biāo)簽,0.6是閾值,0.4是NMS(非極大值抑制)的閾值。
6. 將以上代碼封裝成一個(gè)可執(zhí)行軟件.exe,可以使用Java打包工具,如Maven、Gradle等進(jìn)行打包。
以上是使用DL4J調(diào)用yolo訓(xùn)練好的.pt模型的基本步驟,具體實(shí)現(xiàn)還需要根據(jù)實(shí)際情況進(jìn)行調(diào)整和優(yōu)化。
到此這篇關(guān)于使用Java調(diào)用Yolo模型的方法與步驟的文章就介紹到這了,更多相關(guān)Java調(diào)用Yolo模型內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java如何通過(guò)屬性名獲取Object對(duì)象屬性值
這篇文章主要介紹了Java如何通過(guò)屬性名獲取Object對(duì)象屬性值問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07使用Hibernate根據(jù)實(shí)體類(lèi)自動(dòng)生成表的方法
這篇文章主要介紹了使用Hibernate根據(jù)實(shí)體類(lèi)自動(dòng)生成表的方法,該篇提供了兩種方法,可以根據(jù)需要選擇其一,希望對(duì)你有所幫助,如有不對(duì)的地方還望指正2023-03-03微信公眾號(hào) 網(wǎng)頁(yè)授權(quán)登錄及code been used解決詳解
這篇文章主要介紹了微信公眾號(hào) 網(wǎng)頁(yè)授權(quán)登錄及code been used解決詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-07-07java代碼抓取網(wǎng)頁(yè)郵箱的實(shí)現(xiàn)方法
下面小編就為大家?guī)?lái)一篇java代碼抓取網(wǎng)頁(yè)郵箱的實(shí)現(xiàn)方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-06-06SpringBoot與SpringCloud的版本對(duì)應(yīng)關(guān)系解讀
本文介紹了SpringBoot與SpringCloud的版本對(duì)應(yīng)關(guān)系,提供了一個(gè)官方的版本對(duì)應(yīng)表,并給出了個(gè)人的一些經(jīng)驗(yàn)總結(jié)2024-12-12