如何将图像转换为灰度opengl c ++

时间:2018-04-16 17:46:40

标签: c++ opengl grayscale

任何人都知道如何转换为灰度,下面是我需要使用的一些框架代码。具体来说,转换"之前"到灰度, 应用Sobel边缘检测卷积滤波器,并存储 结果"在"之后。之前必须是非空的。

template <typename color_depth> void 
edge_detect(gfx::image<color_depth>& after,
const gfx::image<color_depth>& before) {

  // Check arguments.
  assert(!before.empty());

  // TODO: replace this function body with working code. Make sure
  // to delete this comment.

  // Hint: Use the grayscale(...) and extend_edges(...) filters to
  // prepare for the Sobel convolution. Then compute the Sobel
  // operator one pixel at a time. Finally use crop_extended_edges
  // to un-do the earlier extend_edges.

}

1 个答案:

答案 0 :(得分:2)

这看起来像是一个家庭作业问题所以我不会给出完整的实施。我也无法分辨你是想在CPU上还是在着色器中转换为灰度。无论您在何处执行转换,公式都是相同的。

由于您丢弃信息以及最终结果看起来是否正确,因此没有确定的转换为灰度的方法是完全主观的。以下是从RGB转换为灰度的一些常用方法:

一种天真的方法是找到具有最高值的颜色通道,然后使用它。

grey = max(colour.r, max(colour.g, colour.b));

天真的方法会受到影响,如果图像的某些区域不包含具有最高值的颜色,则会完全丢失细节。为了防止这种情况,我们可以使用所有颜色组件的简单平均值。

grey = (colour.r + colour.g + colour.b) / 3.0;

“更好”的方法是使用luma值。人眼比其他人更好地感知一些颜色波长。因此,如果我们对这些颜色给予更多的重量,我们就会产生更合理的灰度。

grey = dot_product(colour, vec3(0.299, 0.587, 0.114));

另一种方法是“去饱和”图像。这涉及首先从RGB颜色空间转换为HSL。然后将饱和度降低到零。