dsb238100 2016-10-14 08:26

# 如何获取image.RGBA或任何其他类型的特定像素的几何？

I wish there was something like image.Point struct but instead it was pixel based, if that makes sense.

Say I have loaded and decoded an `image.RGBA` with size(bounds) of 300x300. How can I get the exact coordinate of the middle of the image in `image.Point` or `fixed.Point26_6`?

• 写回答

#### 1条回答默认 最新

• duanhe6464 2016-10-14 09:28
关注

`image.RGBA` is a concrete implementation of the general `image.Image` interface.

It has an `Image.Bounds()` method:

``````// Bounds returns the domain for which At can return non-zero color.
// The bounds do not necessarily contain the point (0, 0).
Bounds() Rectangle
``````

Important to note that the top-left corner of the image might not be at the zero point `(0, 0)` (although generally it is).

So the geometry of the image is handed to you as a value of `image.Rectangle`:

``````type Rectangle struct {
Min, Max Point
}
``````

To handle the general case (where top-left might not be `(0, 0)`), you have to account both the `Min` and `Max` points to to calculate the center point:

``````cx := (r.Min.X + r.Max.X)/2
cy := (r.Min.Y + r.Max.Y)/2
``````

Another solution is to use `Rectangle.Dx()` and `Rectangle.Dy()`:

``````cx := r.Min.X + r.Dx()/2
cy := r.Min.Y + r.Dy()/2
``````

And there is an `image.Point` struct type. To get the center point as a value of `image.Point`:

``````cp := image.Point{(r.Min.X + r.Max.X) / 2, (r.Min.Y + r.Max.Y) / 2}
``````

Or:

``````cp := image.Point{r.Min.X + r.Dx()/2, r.Min.Y + r.Dy()/2}
``````

See this example:

``````r := image.Rect(0, 0, 300, 100)
fmt.Println(r)
cp := image.Point{(r.Min.X + r.Max.X) / 2, (r.Min.Y + r.Max.Y) / 2}
fmt.Println(cp)

cp = image.Point{r.Min.X + r.Dx()/2, r.Min.Y + r.Dy()/2}
fmt.Println(cp)
``````

Output (try it on the Go Playground):

``````(0,0)-(300,100)
(150,50)
(150,50)
``````
本回答被题主选为最佳回答 , 对您是否有帮助呢?
评论

#### 悬赏问题

• ¥15 ros的rviz仿真机器人
• ¥15 关于#linux#的问题（输入输出错误）：出现这个界面接着我重新装系统，又让修电脑的师傅帮我扫描硬盘（没有问题）用着用着又卡死（相关搜索：固态硬盘）
• ¥15 cv::resize不同线程时间不同
• ¥15 web课程，怎么做啊😭没好好听课 根本不知道怎么下手
• ¥15 做一个关于单片机的比较难的代码，然后搞一个PPT进行解释
• ¥15 python提取.csv文件中的链接会经常出现爬取失败
• ¥15 数据结构中的数组地址问题
• ¥15 maya的mel里，怎样先选择模型A，然后利用mel脚本自动选择有相同名字的模型B呢。
• ¥15 Python题，根本不会啊
• ¥15 会会信号与系统和python的来