点击下方卡片,关注“机器视觉与AI深度学习”
视觉/图像重磅干货,第一时间送达!
你是否曾经发现自己要等待很长时间才能处理一个装满图片的文件夹?无论是将它们转换为灰度图还是执行其他图像处理任务,如果您在单个线程中处理所有内容,处理大型数据集可能会非常慢。幸运的是,并行计算可以解决这个问题!
本文中我们将介绍如何使用并行计算来加速常见的计算机视觉任务:将图像转换为灰度图。我们将研究两个示例:一个使用Joblib库在Python中编写,另一个使用 OpenMP 在 C++中编写。
Joblib简介:
🚀 Python中使用Joblib 加速
import os
import cv2
from glob import glob
from joblib import Parallel, delayed
input_folder = 'images/'
output_folder = 'output/'
def convert_to_grayscale(image_path, output_folder):
img = cv2.imread(image_path)
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
output_path = os.path.join(output_folder, os.path.basename(image_path))
cv2.imwrite(output_path, gray_img)
if __name__ == "__main__":
# get a list of abs path for all .jpg files whitin input_folder
image_files = glob(f"{input_folder}/*.jpg")
# Parallel processing using Joblib
Parallel(n_jobs=-1, backend="threading")(delayed(convert_to_grayscale)(image, output_folder) for image in image_files)
sudo apt-get install libopencv-dev
g++ -fopenmp -o image_converter image_converter.cpp `pkg-config --cflags --libs opencv4`
#include <opencv2/opencv.hpp>
#include <omp.h>
#include <filesystem>
#include <string>
void convert_to_grayscale(const std::string& input_path, const std::string& output_folder)
{
cv::Mat img = cv::imread(input_path);
cv::Mat gray_img;
cv::cvtColor(img, gray_img, cv::COLOR_BGR2GRAY);
std::string output_path = output_folder + "/" + std::filesystem::path(input_path).filename().string();
cv::imwrite(output_path, gray_img);
}
int main()
{
std::string input_folder = "images/";
std::string output_folder = "output/";
std::vector<std::string> image_files;
for (const auto& entry : std::filesystem::directory_iterator(input_folder))
{
image_files.emplace_back(entry.path().string());
}
// Parallel processing using OpenMP
#pragma omp parallel for
for (size_t i = 0; i < image_files.size(); ++i)
{
convert_to_grayscale(image_files[i], output_folder);
}
return 0;
}
https://github.com/Gabriellgpc/multhreading-image-processing?source=post_page-----9a8895115ef8--------------------------------