高亮显示图像

Highlighting an image

本文关键字:图像 显示图 显示 高亮      更新时间:2023-10-16

我的导师写道"突出显示图像中对象的一种方法是使阈值(T1)以下的所有像素为0,而阈值(T2)以上的所有像素均为255。使用以下原型编写一个函数来突出显示图像:

void highlight(int image[][MAXHEIGHT],int width, int height, int t1, int t2)

编写一个主程序,从用户输入t1和t2,高亮显示图像,然后写入图像。"

我已经有了可以读取和写入图像的功能,但我不知道如何更改图像的像素。

到目前为止的代码:

#include <iostream>
#include <cassert>
#include <cstdlib>
#include <fstream>
using namespace std;
const int MAXWIDTH = 512;
const int MAXHEIGHT = 512;
// reads a PGM file.
void readImage(int image[][MAXHEIGHT], int &width, int &height) {
  char c;
  int x;
  ifstream instr;
  instr.open("city.pgm");
  cout << "This is running " << endl;
  // read the header P2
  instr >> c;  assert(c == 'P');
  instr >> c;  assert(c == '2');
  // skip the comments (if any)
  while ((instr>>ws).peek() == '#') { instr.ignore(4096, 'n'); }
  instr >> width; 
  instr >> height;
  assert(width <= MAXWIDTH);
  assert(height <= MAXHEIGHT);
  int max;
  instr >> max;
  assert(max == 255);
  for (int row = 0; row < height; row++) 
    for (int col = 0; col < width; col++) 
      instr >> image[col][row];
  instr.close();
  return;
}
// Writes a PGM file
void writeImage(int image[][MAXHEIGHT], int width, int height) {
  ofstream ostr;
  ostr.open("outImage.pgm");
  if (ostr.fail()) {
    cout << "Unable to write filen";
    exit(1);
  };
  // print the header
  ostr << "P2" << endl;
  // width, height
  ostr << width << ' '; 
  ostr << height << endl;
  ostr << 255 << endl;
  for (int row = 0; row < height; row++) {
    for (int col = 0; col < width; col++) {
      assert(image[col][row] < 256);
      assert(image[col][row] >= 0);
      ostr << image[col][row] << ' ';
      // lines should be no longer than 70 characters
      if ((col+1)%16 == 0) ostr << endl;
    }
    ostr << endl;
  }
  ostr.close();
  return;
}

int main ()
{
 int image[MAXWIDTH][MAXHEIGHT], width, height, t1, t2;
 readImage (image, width, height);
 writeImage (image, width, height);
 return 0;
}

在您已经编写了所有代码,包括对PGM标头的分析之后,我不明白您为什么要这样做。

void highlight(int image[][MAXHEIGHT],int width, int height, int t1, int t2) {
    for (int row = 0; row < height; row++) 
        for (int col = 0; col < width; col++) 
            if (image[col][row]<t1) 
                image[col][row] =0; 
            else if (image[col][row]>t2) 
                image[col][row]=255;
}

编辑:我已经使用了您的索引方案,它似乎是一致的,应该可以工作。然而,通常的做法是表示2D阵列,使得行是第一个索引,列是第二个索引。通过这种方式,一行由连续的元素表示