图片处理(Picture Lab)活动7:镜像图片的一部分

陈 欣发布

有时你只想镜像图像的一部分。下图中希腊神庙屋顶的三角墙部分有所缺损。你可以使用探索工具来确认需要镜像的区域,来生成右侧补全后的结果。在确认边界之后,你会发现镜像区域是在27至96行以及13至275列之间(包括边缘)。你可以修改行和列在循环中的起止点来镜像图片的一部分。

为了仅处理我们感兴趣的部分,按照下面mirrorTemple method所示修改嵌套for循环的起止点。该method还计算当前列与mirrorPoint间的距离,之后再加上mirrorPoint求得右侧对应像素的列号。

public void mirrorTemple()
{
  int mirrorPoint = 276;
  Pixel leftPixel = null;
  Pixel rightPixel = null;
  int count = 0;
  Pixel[][] pixels = this.getPixels2D();
   
  // loop through the rows
  for (int row = 27; row < 97; row++)
  {
    // loop from 13 to just before the mirror point
    for (int col = 13; col < mirrorPoint; col++)
    {
      leftPixel = pixels[row][col];      
      rightPixel = pixels[row]                       
                       [mirrorPoint - col + mirrorPoint];
      rightPixel.setColor(leftPixel.getColor());
    }
  }
}

可以用PictureTester中的testMirrorTemple method来测试它。

leftPixel = pixels[row][col];这一语句到底执行了多少次?嵌套循环执行次数的公式是外层循环次数乘以内层循环次数。外层循环遍历每一行,在内层循环之外。内层循环遍历行中的每一列,在行的循环以内。

外层循环执行了多少次?它以row等于27开始,在其达到97之后结束,因此最后循环的row值为96。为计算循环次数,我们需要把结束值减开始值再加一,因而共执行了70次。同理,易得内层循环执行了263次,因而总的执行次数是两者之积18,410。

问题

  1. 以下嵌套for循环的总执行次数是多少?
    for (int row = 7; row < 17; row++)
      for (int col = 6; col < 15; col++)
  2. 以下嵌套for循环的总执行次数是多少?
    for (int row = 5; row <= 11; row++)
      for (int col = 3; col <= 18; col++)

练习

  1. mirrorTemple method中增加一个整数变量count以验证循环总执行次数。count初始值为0,并随着循环逐渐累加。在嵌套循环结束后打印出count的值。
  2. 编写mirrorArms以把雪人(snowman.jpg)的手臂镜像,生成一个四臂雪人。在class PictureTester中创建一个测试新method的static method,并确保在PictureTestermain method中调用它。
  3. 编写mirrorGull以把海鸥(seagull.jpg)复制到右边,让沙滩上有前后两只海鸥。在class PictureTester中创建一个测试新method的static method,并确保在PictureTestermain method中调用它。

陈 欣

AADPS创始人

0 条评论

发表回复