windows C++-创建图像处理的异步消息(三)

news2024/10/9 5:37:18
完整实例 

以下代码显示完整示例是基于wmain 函数和 GDI+ 库,并调用 ProcessImages 函数以处理 默认目录中的 JPEG 文件。

// image-processing-network.cpp
// compile with: /DUNICODE /EHsc image-processing-network.cpp /link gdiplus.lib
#include <windows.h>
#include <gdiplus.h>
#include <iostream>
#include <map>
#include <agents.h>
#include <ppl.h>

using namespace concurrency;
using namespace Gdiplus;
using namespace std;

// Retrieves the red, green, and blue components from the given
// color value.
void GetRGB(DWORD color, BYTE& r, BYTE& g, BYTE& b)
{
   r = static_cast<BYTE>((color & 0x00ff0000) >> 16);
   g = static_cast<BYTE>((color & 0x0000ff00) >> 8);
   b = static_cast<BYTE>((color & 0x000000ff));
}

// Creates a single color value from the provided red, green, 
// and blue components.
DWORD MakeColor(BYTE r, BYTE g, BYTE b)
{
   return (r<<16) | (g<<8) | (b);
}

// Calls the provided function for each pixel in a Bitmap object.
void ProcessImage(Bitmap* bmp, const function<void (DWORD&)>& f)
{
   int width = bmp->GetWidth();
   int height = bmp->GetHeight();

   // Lock the bitmap.
   BitmapData bitmapData;
   Rect rect(0, 0, bmp->GetWidth(), bmp->GetHeight());
   bmp->LockBits(&rect, ImageLockModeWrite, PixelFormat32bppRGB, &bitmapData);

   // Get a pointer to the bitmap data.
   DWORD* image_bits = (DWORD*)bitmapData.Scan0;

   // Call the function for each pixel in the image.
   parallel_for (0, height, [&, width](int y)
   {      
      for (int x = 0; x < width; ++x)
      {
         // Get the current pixel value.
         DWORD* curr_pixel = image_bits + (y * width) + x;

         // Call the function.
         f(*curr_pixel);
      }
   });

   // Unlock the bitmap.
   bmp->UnlockBits(&bitmapData);
}

// Converts the given image to grayscale.
Bitmap* Grayscale(Bitmap* bmp) 
{
   ProcessImage(bmp, 
      [](DWORD& color) {
         BYTE r, g, b;
         GetRGB(color, r, g, b);

         // Set each color component to the average of 
         // the original components.
         BYTE c = (static_cast<WORD>(r) + g + b) / 3;
         color = MakeColor(c, c, c);
      }
   );
   return bmp;
}

// Applies sepia toning to the provided image.
Bitmap* Sepiatone(Bitmap* bmp) 
{
   ProcessImage(bmp, 
      [](DWORD& color) {
         BYTE r0, g0, b0;
         GetRGB(color, r0, g0, b0);

         WORD r1 = static_cast<WORD>((r0 * .393) + (g0 *.769) + (b0 * .189));
         WORD g1 = static_cast<WORD>((r0 * .349) + (g0 *.686) + (b0 * .168));
         WORD b1 = static_cast<WORD>((r0 * .272) + (g0 *.534) + (b0 * .131));

         color = MakeColor(min(0xff, r1), min(0xff, g1), min(0xff, b1));
      }
   );
   return bmp;
}

// Applies the given color mask to each pixel in the provided image.
Bitmap* ColorMask(Bitmap* bmp, DWORD mask)
{
   ProcessImage(bmp, 
      [mask](DWORD& color) {
         color = color & mask;
      }
   );
   return bmp;
}

// Darkens the provided image by the given amount.
Bitmap* Darken(Bitmap* bmp, unsigned int percent)
{
   if (percent > 100)
      throw invalid_argument("Darken: percent must less than 100.");

   double factor = percent / 100.0;

   ProcessImage(bmp, 
      [factor](DWORD& color) {
         BYTE r, g, b;
         GetRGB(color, r, g, b);
         r = static_cast<BYTE>(factor*r);
         g = static_cast<BYTE>(factor*g);
         b = static_cast<BYTE>(factor*b);
         color = MakeColor(r, g, b);
      }
   );
   return bmp;
}

// Determines which color component (red, green, or blue) is most dominant
// in the given image and returns a corresponding color mask.
DWORD GetColorDominance(Bitmap* bmp)
{
   // The ProcessImage function processes the image in parallel.
   // The following combinable objects enable the callback function
   // to increment the color counts without using a lock.
   combinable<unsigned int> reds;
   combinable<unsigned int> greens;
   combinable<unsigned int> blues;

   ProcessImage(bmp, 
      [&](DWORD& color) {
         BYTE r, g, b;
         GetRGB(color, r, g, b);
         if (r >= g && r >= b)
            reds.local()++;
         else if (g >= r && g >= b)
            greens.local()++;
         else
            blues.local()++;
      }
   );
   
   // Determine which color is dominant and return the corresponding
   // color mask.

   unsigned int r = reds.combine(plus<unsigned int>());
   unsigned int g = greens.combine(plus<unsigned int>());
   unsigned int b = blues.combine(plus<unsigned int>());

   if (r + r >= g + b)
      return 0x00ff0000;
   else if (g + g >= r + b)
      return 0x0000ff00;
   else
      return 0x000000ff;
}

// Retrieves the class identifier for the given MIME type of an encoder.
int GetEncoderClsid(const WCHAR* format, CLSID* pClsid)
{
   UINT  num = 0;          // number of image encoders
   UINT  size = 0;         // size of the image encoder array in bytes

   ImageCodecInfo* pImageCodecInfo = nullptr;

   GetImageEncodersSize(&num, &size);
   if(size == 0)
      return -1;  // Failure

   pImageCodecInfo = (ImageCodecInfo*)(malloc(size));
   if(pImageCodecInfo == nullptr)
      return -1;  // Failure

   GetImageEncoders(num, size, pImageCodecInfo);

   for(UINT j = 0; j < num; ++j)
   {
      if( wcscmp(pImageCodecInfo[j].MimeType, format) == 0 )
      {
         *pClsid = pImageCodecInfo[j].Clsid;
         free(pImageCodecInfo);
         return j;  // Success
      }    
   }

   free(pImageCodecInfo);
   return -1;  // Failure
}

// A synchronization primitive that is signaled when its 
// count reaches zero.
class countdown_event
{
public:
   countdown_event(unsigned int count = 0)
      : _current(static_cast<long>(count)) 
   {
      // Set the event if the initial count is zero.
      if (_current == 0L)
         _event.set();
   }
     
   // Decrements the event counter.
   void signal() {
      if(InterlockedDecrement(&_current) == 0L) {
         _event.set();
      }
   }

   // Increments the event counter.
   void add_count() {
      if(InterlockedIncrement(&_current) == 1L) {
         _event.reset();
      }
   }
   
   // Blocks the current context until the event is set.
   void wait() {
      _event.wait();
   }
 
private:
   // The current count.
   volatile long _current;
   // The event that is set when the counter reaches zero.
   event _event;

   // Disable copy constructor.
   countdown_event(const countdown_event&);
   // Disable assignment.
   countdown_event const & operator=(countdown_event const&);
};

// Demonstrates how to set up a message network that performs a series of 
// image processing operations on each JPEG image in the given directory and
// saves each altered image as a Windows bitmap.
void ProcessImages(const wstring& directory)
{
   // Holds the number of active image processing operations and 
   // signals to the main thread that processing is complete.
   countdown_event active(0);

   // Maps Bitmap objects to their original file names.
   map<Bitmap*, wstring> bitmap_file_names;
      
   //
   // Create the nodes of the network.
   //

   // Loads Bitmap objects from disk.
   transformer<wstring, Bitmap*> load_bitmap(
      [&](wstring file_name) -> Bitmap* {
         Bitmap* bmp = new Bitmap(file_name.c_str());
         if (bmp != nullptr)
            bitmap_file_names.insert(make_pair(bmp, file_name));
         return bmp;
      }
   );

   // Holds loaded Bitmap objects.
   unbounded_buffer<Bitmap*> loaded_bitmaps;
  
   // Converts images that are authored by Tom to grayscale.
   transformer<Bitmap*, Bitmap*> grayscale(
      [](Bitmap* bmp) {
         return Grayscale(bmp);
      },
      nullptr,
      [](Bitmap* bmp) -> bool {
         if (bmp == nullptr)
            return false;

         // Retrieve the artist name from metadata.
         UINT size = bmp->GetPropertyItemSize(PropertyTagArtist);
         if (size == 0)
            // Image does not have the Artist property.
            return false;

         PropertyItem* artistProperty = (PropertyItem*) malloc(size);
         bmp->GetPropertyItem(PropertyTagArtist, size, artistProperty);
         string artist(reinterpret_cast<char*>(artistProperty->value));
         free(artistProperty);
         
         return (artist.find("Tom ") == 0);
      }
   );
   
   // Removes the green and blue color components from images that have red as
   // their dominant color.
   transformer<Bitmap*, Bitmap*> colormask(
      [](Bitmap* bmp) {
         return ColorMask(bmp, 0x00ff0000);
      },
      nullptr,
      [](Bitmap* bmp) -> bool { 
         if (bmp == nullptr)
            return false;
         return (GetColorDominance(bmp) == 0x00ff0000);
      }
   );

   // Darkens the color of the provided Bitmap object.
   transformer<Bitmap*, Bitmap*> darken([](Bitmap* bmp) {
      return Darken(bmp, 50);
   });

   // Applies sepia toning to the remaining images.
   transformer<Bitmap*, Bitmap*> sepiatone(
      [](Bitmap* bmp) {
         return Sepiatone(bmp);
      },
      nullptr,
      [](Bitmap* bmp) -> bool { return bmp != nullptr; }
   );

   // Saves Bitmap objects to disk.
   transformer<Bitmap*, Bitmap*> save_bitmap([&](Bitmap* bmp) -> Bitmap* {
      // Replace the file extension with .bmp.
      wstring file_name = bitmap_file_names[bmp];
      file_name.replace(file_name.rfind(L'.') + 1, 3, L"bmp");
      
      // Save the processed image.
      CLSID bmpClsid;
      GetEncoderClsid(L"image/bmp", &bmpClsid);      
      bmp->Save(file_name.c_str(), &bmpClsid);

      return bmp;
   });

   // Deletes Bitmap objects.
   transformer<Bitmap*, Bitmap*> delete_bitmap([](Bitmap* bmp) -> Bitmap* {      
      delete bmp;
      return nullptr;
   });

   // Decrements the event counter.
   call<Bitmap*> decrement([&](Bitmap* _) {      
      active.signal();
   });

   //
   // Connect the network.
   //   
   
   load_bitmap.link_target(&loaded_bitmaps);
   
   loaded_bitmaps.link_target(&grayscale);
   loaded_bitmaps.link_target(&colormask);   
   colormask.link_target(&darken);
   loaded_bitmaps.link_target(&sepiatone);
   loaded_bitmaps.link_target(&decrement);
   
   grayscale.link_target(&save_bitmap);
   darken.link_target(&save_bitmap);
   sepiatone.link_target(&save_bitmap);
   
   save_bitmap.link_target(&delete_bitmap);
   delete_bitmap.link_target(&decrement);
   
   // Traverse all files in the directory.
   wstring searchPattern = directory;
   searchPattern.append(L"\\*");

   WIN32_FIND_DATA fileFindData;
   HANDLE hFind = FindFirstFile(searchPattern.c_str(), &fileFindData);
   if (hFind == INVALID_HANDLE_VALUE) 
      return;
   do
   {
      if (!(fileFindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
      {
         wstring file = fileFindData.cFileName;

         // Process only JPEG files.
         if (file.rfind(L".jpg") == file.length() - 4)
         {
            // Form the full path to the file.
            wstring full_path(directory);
            full_path.append(L"\\");
            full_path.append(file);

            // Increment the count of work items.
            active.add_count();

            // Send the path name to the network.
            send(load_bitmap, full_path);
         }
      }
   }
   while (FindNextFile(hFind, &fileFindData) != 0); 
   FindClose(hFind);
      
   // Wait for all operations to finish.
   active.wait();
}

int wmain()
{
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR           gdiplusToken;

   // Initialize GDI+.
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, nullptr);

   // Perform image processing.
   // TODO: Change this path if necessary.
   ProcessImages(L"C:\\Users\\Public\\Pictures\\Sample Pictures");

   // Shutdown GDI+.
   GdiplusShutdown(gdiplusToken);
}

下图显示了示例输出。 每个源图像都在其经过修改的对应图像上方。

Lighthouse 由 Tom Alphin 创作,因此转换为灰度。 Chrysanthemum、Desert、Koala 和 Tulips 将红色作为主色,因此移除了蓝色和绿色分量并变暗。 Hydrangeas、Jellyfish 和 Penguins 与默认条件匹配,因此应用了棕色调。 

编译代码

复制示例代码,并将它粘贴到 Visual Studio 项目中,或粘贴到名为 image-processing-network.cpp 的文件中,再在 Visual Studio 命令提示符窗口中运行以下命令(素材自行上准备)。

cl.exe /DUNICODE /EHsc image-processing-network.cpp /link gdiplus.lib

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2198147.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

制造企业MES管理系统的应用策略与实施路径

在智能制造浪潮的席卷之下&#xff0c;MES管理系统作为连接生产计划与车间操作的核心桥梁&#xff0c;其战略地位愈发显著。本文旨在深入剖析MES管理系统在智能制造转型中的核心价值、实施策略及实践路径&#xff0c;为制造企业探索智能化生产之路提供实践指导与灵感启发。 MES…

火山引擎边缘智能亮相“地瓜机器人开发者大会”,推动端侧大模型应用与落地

9 月 20 日&#xff0c;2024 地瓜机器人开发者日暨新品发布在深圳科创学院南山总部成功举办&#xff0c;火山引擎边缘智能受邀出席此次会议。会议以“加速智能生长”为主题&#xff0c;发布了地瓜机器人新一代机器人开发者套件 RDK X5 &#xff0c;同时&#xff0c;会议汇聚了中…

Puppeteer自动化:使用JavaScript定制PDF下载

引言 在现代的Web开发中&#xff0c;自动化已经成为提高效率和减少重复劳动的重要手段。Puppeteer 是一个强大的Node.js库&#xff0c;提供了对无头Chrome或Chromium的控制&#xff0c;可以用于生成网页快照、抓取数据、自动化测试等任务。其中&#xff0c;生成PDF文件是一个常…

【TOP K】leetcode 215.数组中第K个最大的元素

1 题目描述 题目链接&#xff1a;数组中第K个最大的元素 2 题目解析 首先区分 第K个最大的元素和 第K个不同的元素 考虑使用什么数据结构&#xff1f; 使用堆的数据结构&#xff0c;可以使用priority_queue&#xff0c;然后 建大堆&#xff0c;这样大的元素就在前面。接着…

爬虫案例——爬取腾讯社招

案例需求&#xff1a; 1.爬取腾讯社招的数据&#xff08;搜索 | 腾讯招聘&#xff09;包括岗位名称链接时间公司名称 2.爬取所有页&#xff08;翻页&#xff09; 3.利用jsonpath进行数据解析 4.保存数据&#xff1a;txt文本形式和excel文件两种形式 解析&#xff1a; 1.分…

9.16贪心算法

定义&#xff1a;贪心算法是一种逐步构建解决方案的算法&#xff0c;每次选择当前最优的局部解&#xff0c;期望通过局部最优解的累积&#xff0c;最终获得全局最优解​​​​​​典型例题&#xff1a; 1.找零问题--蓝桥云课 解决方案&#xff1a;先找大额&#xff0c;再找小额…

FreeRTOS学习笔记内置部分公司面试题目(更新中)

1. 简介 1.1 RTOS简介 RTOS(实时操作系统)是指一类系统&#xff0c;如 FreeRTOS&#xff0c;uC/OS&#xff0c;RTX&#xff0c;RT-Thread 等&#xff0c;都是 RTOS 类操作系统。 FreeRTOS 由美国的 Richard Barry 于 2003 年发布。 FreeRTOS 于 2017 年被亚马逊收购&#x…

【EXCEL数据处理】000022 案例 保姆级教程,附多个操作案例。EXCEL邮件合并工具

前言&#xff1a;哈喽&#xff0c;大家好&#xff0c;今天给大家分享一篇文章&#xff01;创作不易&#xff0c;如果能帮助到大家或者给大家一些灵感和启发&#xff0c;欢迎收藏关注哦 &#x1f495; 目录 【EXCEL数据处理】000022 案例 保姆级教程&#xff0c;附多个操作案例。…

如何基于 RLHF 来优化 ChatGPT 类型的大语言模型

&#x1f6b4;前言 对于ChatGPT来说&#xff0c;RLHF是其训练的核心。所谓RLHF&#xff0c;即Reinforcement Learning with Human Feedback&#xff0c;基于人类反馈的强化学习。这项技术通过结合模型自身的生成能力和人类专家的反馈&#xff0c;为改进文本生成质量提供了新的…

云计算Openstack Horizon

OpenStack是一个开源的云计算平台&#xff0c;提供了构建和管理云计算环境所需的软件工具。而Horizon则是OpenStack的一个关键组件&#xff0c;它是基于Web的用户界面&#xff0c;为用户提供了一种直观、便捷的方式来管理和使用OpenStack资源。 一、技术原理 Horizon是一个基…

CloudStack计算节点配置

主机信息 CloudStack计算节点 任务1、计算节点基础环境准备 1)需要创建2张网卡&#xff01;&#xff01;&#xff01;】 2)VMware Workstation 中设置网卡模式为NAT&#xff0c;在“网络编辑器”中设置DHCP&#xff0c;网关设置为192.168.100.1&#xff0c;地址段为192.168.…

【记录】PPT|PPT 箭头相交怎么跨过

众所周知&#xff0c;在PPT中实现“跨线”效果并非直接可行&#xff0c;这一功能仅存在于Visio中。然而&#xff0c;通过一些巧妙的方法&#xff0c;我们可以在PPT中模拟出类似的效果。怎么在PPT中画交叉但不重叠的线-百度经验中介绍了一种方法&#xff0c;而本文将介绍一种改进…

初探OceanBase 4.x单机环境下如何进行主备架构搭建

本文来自OceanBase 用户的体验分享 &#xff08;以下简称 OB&#xff09;&#xff0c;已经开源了3年左右&#xff0c;其间从3.x版本演进至4.x版本&#xff0c;发生了许多变化。对一个DBer而言&#xff0c;最为关切的是如何高效运用OB&#xff0c;以及是否能实现如同应用MySQL般…

计算机毕业设计 基于Hadoop的智慧校园数据共享平台的设计与实现 Python毕业设计 Python毕业设计选题 Spark 大数据【附源码+安装调试】

博主介绍&#xff1a;✌从事软件开发10年之余&#xff0c;专注于Java技术领域、Python人工智能及数据挖掘、小程序项目开发和Android项目开发等。CSDN、掘金、华为云、InfoQ、阿里云等平台优质作者✌ &#x1f345;文末获取源码联系&#x1f345; &#x1f447;&#x1f3fb; 精…

解析一体式IO与分布式IO:从架构到应用

在工业自动化领域&#xff0c;IO&#xff08;输入/输出&#xff09;系统扮演着举足轻重的角色。它们不仅负责数据的采集和控制指令的发送&#xff0c;还直接影响到系统的灵活性、可靠性和成本效益。明达技术将为您介绍一体式IO和分布式IO在架构及应用层的主要区别&#xff0c;帮…

Unity 从零开始的框架搭建1-1 unity中对象调用的三种方式的优缺点分析【干货】

该文章专栏是向QFrameWork作者凉鞋老师学习总结得来&#xff0c;吃水不忘打井人&#xff0c;不胜感激 Unity 框架搭建学习笔记1-1&#xff0c;前一个1代表凉鞋的第一季教程&#xff0c;后一个1代表该季第一篇我的文章 unity中对象调用的三种方式 方法调用&#xff0c;例如&…

计算机毕业设计 基于Python的智能停车系统的设计与实现 Python+Django+Vue 前后端分离 附源码 讲解 文档

&#x1f34a;作者&#xff1a;计算机编程-吉哥 &#x1f34a;简介&#xff1a;专业从事JavaWeb程序开发&#xff0c;微信小程序开发&#xff0c;定制化项目、 源码、代码讲解、文档撰写、ppt制作。做自己喜欢的事&#xff0c;生活就是快乐的。 &#x1f34a;心愿&#xff1a;点…

对高危漏洞“Docker Engine API is accessible without authentication”的修复

一.背景 之前文章maven项目容器化运行之1-基于1Panel软件将docker镜像构建能力分享给局域网_1panel 构建镜像-CSDN博客将1Panel软件的Doocker端口给到了局域网&#xff0c;安全组兄弟扫描认为是高危漏洞&#xff0c;可能导致攻击者获取对Docker主机的完全控制权。 二.修复的建…

单兵可背负履带式全地形无人车技术详解

单兵可背负履带式全地形无人车是一种专为复杂环境和多样化任务设计的智能装备&#xff0c;具备出色的地面适应性、越野性能以及灵活的操控性。以下是对其技术的详细解析&#xff1a; 一、驱动技术 履带式驱动&#xff1a;采用履带式驱动技术&#xff0c;通过履带与地面的广泛…

动手学深度学习9.3. 深度循环神经网络-笔记练习(PyTorch)

本节课程地址&#xff1a;58 深层循环神经网络【动手学深度学习v2】_哔哩哔哩_bilibili 本节教材地址&#xff1a;9.3. 深度循环神经网络 — 动手学深度学习 2.0.0 documentation (d2l.ai) 本节开源代码&#xff1a;...>d2l-zh>pytorch>chapter_multilayer-perceptr…