首页 > 其他分享 >Go - Flipping an Image Upside Down

Go - Flipping an Image Upside Down

时间:2023-10-10 11:34:52浏览次数:51  
标签:color Image pixels Down into grid file Go image

Problem: You want to flip an image upside down.


Solution: Convert an image to a grid of pixels. Swap the positions of the top and bottom pairs of pixels and move down to swap the next pair until all the pixel positions are swapped. Convert the grid of pixels back into a flipped image.

 

The Image implementations (for example, image.NRGBA ) have a slice of bytes that represent pixels in the image. That’s not the most intuitive way to represent a raster image. What’s more common is a grid of pixels (because a raster image is literally a grid of pixels), so that’s the first thing you want to do — convert an image.NRGBA to a grid of pixels.

In the image package , a pixel is represented by the type color.Color so you’re going to create a 2D slice of color.Color pixels. You will extend the load function from before to do this so you can return the grid:

func   load ( filePath   string )   ( grid   [][] color . Color )   { 
      //  open  the  file  and  decode  the  contents  into  an  image 
      file ,   err   :=   os . Open ( filePath ) 
      if   err   !=   nil   { 
          log . Println ( "Cannot  read  file:" ,   err ) 
      } 
      defer   file . Close () 
      img ,   _ ,   err   :=   image . Decode ( file ) 
      if   err   !=   nil   { 
          log . Println ( "Cannot  decode  file:" ,   err ) 
      } 
      //  create  and  return  a  grid  of  pixels 
      size   :=   img . Bounds (). Size () 
      for   i   :=   0 ;   i   <   size . X ;   i ++   { 
          var   y   [] color . Color 
          for   j   :=   0 ;   j   <   size . Y ;   j ++   { 
              y   =   append ( y ,   img . At ( i ,   j )) 
          } 
          grid   =   append ( grid ,   y ) 
      } 
      return 
}

To convert the image into a grid, you need to find out the size of the image. Use the Size method on the Rect struct that is returned from calling the Bounds method on the image. This returns a Point , which gives you the X and Y width and length of the image. Iterate the width and length, and at each pixel position, use the At method to get the pixel color.Color . This will give you a grid of color.Color pixels.

You will also need to extend the save function to let you save the grid of pixels back into a file:

func   save ( filePath   string ,   grid   [][] color . Color )   { 
      //  create  an  image  and  set  the  pixels  using  the  grid 
      xlen ,   ylen   :=   len ( grid ),   len ( grid [ 0 ]) 
      rect   :=   image . Rect ( 0 ,   0 ,   xlen ,   ylen ) 
      img   :=   image . NewNRGBA ( rect ) 
      for   x   :=   0 ;   x   <   xlen ;   x ++   { 
          for   y   :=   0 ;   y   <   ylen ;   y ++   { 
              img . Set ( x ,   y ,   grid [ x ][ y ]) 
          } 
      } 
      //  create  a  file  and  encode  the  image  into  it 
      file ,   err   :=   os . Create ( filePath ) 
      if   err   !=   nil   { 
          log . Println ( "Cannot  create  file:" ,   err ) 
      } 
      defer   file . Close () 
      png . Encode ( file ,   img . SubImage ( img . Rect )) 
}

First, you need to create an image. Using the width and length of the 2D slice, create a Rect to represent the size of the image. Create a new image using the image.NewNRGBA function, passing it the Rect . Then iterate through the grid and at every position, set the color.Color pixel from the grid into the new image.

Finally, take the image and encode it into a file.

Now that you can load an image file into a grid of pixels and save it back into an image file, look at the algorithm you want to use to flip the image upside down:

func   flip ( grid   [][] color . Color )   { 
      for   x   :=   0 ;   x   <   len ( grid );   x ++   { 
          col   :=   grid [ x ] 
          for   y   :=   0 ;   y   <   len ( col ) / 2 ;   y ++   { 
              z   :=   len ( col )   -   y   -   1 
              col [ y ],   col [ z ]   =   col [ z ],   col [ y ] 
          } 
      } 
}

It’s relatively simple to flip the image with a grid of pixels. You simply iterate through each column of the grid and swap the top and bottom pixels. Here’s how you can use this algorithm to flip the image:

func   main ()   { 
      grid   :=   load ( "monalisa.png" ) 
      flip ( grid ) 
      save ( "flipped.png" ,   grid ) 
}

 

标签:color,Image,pixels,Down,into,grid,file,Go,image
From: https://www.cnblogs.com/zhangzhihui/p/17754233.html

相关文章

  • 解决 golang 中 grep console 插件不生效问题
    日志多了以后不好找,idea中的神奇grepconsole在goland竟然不好使了,一番查找下,找到了一个解决方案cmd+shift+a找到Registry找到go.run.processes.with.pty,改为false大功告成原贴:https://github.com/krasa/GrepConsole/issues/175......
  • Go - Creating Images
    Problem: Youwanttocreateanimagefromscratch.Solution: CreateoneoftheImageimplementationstructs(e.g.,NRGBA)andpopulateitwiththeappropriatedata. Asyourememberfromearlier,NRGBAhasthreeattributes:Pix•Asliceofbytesthat......
  • Go通道机制与应用详解
    本文深入探讨了Go语言中通道(Channel)的各个方面,从基础概念到高级应用。文章详细解析了通道的类型、操作方法以及垃圾回收机制,更进一步通过具体代码示例展示了通道在数据流处理、任务调度和状态监控等多个实际应用场景中的作用。本文旨在为读者提供一个全面而深入的理解,以更有效地......
  • go gomail.v2发送邮件报错unencrypted connection
    实现Auth接口typeauthstruct{hoststringusernamestringpasswordstring}func(a*auth)Start(server*smtp.ServerInfo)(protostring,toServer[]byte,errerror){if!server.TLS{advertised:=falsefor_,mechanis......
  • Go - Loading an Image from a File
    Problem: Youwanttoloadanimagefromanimagefile.Solution: Useimage.Decodetodecodedatafromanimagefileintoanimplementationofimage.Image. Ifyouwanttoworkwithanimagefromafile,youhavetoopenupthefileandthendecodeits......
  • MarkDown编辑器常用语法
    1、字体、字号与颜色<fontface="黑体">我是黑体字</font><fontface="微软雅黑">我是微软雅黑</font><fontface="STCAIYUN">我是华文彩云</font><fontcolor=#0099ffsize=7face="黑体">color=#0099ffsize=72face=&q......
  • MongoDB可视化管理工具-MongoDB Compass【转】
    一、引言在使用MongoDB过程中,如果单单依靠命令行操作MongoDB数据库,效率不高而且查看不方便。因此MongoDB官网提供的一个可视化管理工具,叫MongoDBCompass,它集创建数据库、管理集合和文档、运行临时查询、评估和优化查询、性能图表、构建地理查询等功能为一体,很方便。二、......
  • Go - Finding the Shortest Path on a Graph
    Problem: Youwanttofindtheshortestpathbetweentwonodesonaweightedgraph.Solution: UseDijkstra’salgorithmtofindtheshortestpathbetweentwonodes.Dijkstra’salgorithmalsousesapriorityqueue,whichcanbeimplementedusingaminheap.......
  • 论文阅读(一)—— Adding Conditional Control to Text-to-Image Diffusion Models
    ......
  • MongoDB常用查询
    1.数据库数据说明#集合:school#文档:stu#结合字段:id,学号、姓名、电话、性别、年龄、学历、备注#初始化20条数据useschoolfor(varnum=1;num<=20;num++){db.stu.insert({id:num,no:"SN"+num,name:"name"+num,tel:"111......