可视化 如何获取图像中像素的颜色(以C++ (sfml) 为单位)

visual How to get the color of a pixel in an image in C++ (sfml)

本文关键字:颜色 C++ 为单位 sfml 像素 图像 何获取 获取 可视化      更新时间:2023-10-16

我正在制作一个简单的赛车游戏,您可以在赛道上驾驶汽车。 赛道是灰色的,背景是绿色的,每当我在给定点(汽车的前部)上得到的颜色不是灰色时,汽车应该停下来,因为它离开了赛道。

但是,该曲目不是用 sfml 绘制的,而是我制作的下载图像。 那么,只要 rgb 值匹配,是否有任何方法可以在 IMAGE 上获取像素的颜色?

这是执行此操作的伪代码:

游戏运行时
获取颜色(汽车 X 值,汽车 Y 值)
如果颜色不是灰色
,汽车停止

谢谢!

您可以使用适当的方法获取sf::Image中像素的sf::Colorsf::Image::getPixel。它需要 X 和 Y 坐标。

例:

sf::Image track;
if (!track.loadFromFile("track.jpg"))
{
// oops, loading failed, handle it
}
sf::Color color = track.getPixel(0, 0); // gets the color of the upper left corner pixel

你需要使用 sf::Image 的 getPixel(int x, int y) funciton。您的伪代码如下所示:

sf::Image track;
sf::Color grey_color; // You'll need to define what the grey color is.
// Take sf::Color(100, 100, 100) as an example.
if (!track.loadFromFile("track.jpg")) {
std::cout << "Uhoh" << std::endl;
}
while (gameIsRunning) {
sf::Color color_at_car = track.getPixel(car.getx(), car.gety());
if (color_at_car != grey_color) {
car.stop();
}
}

希望这有帮助!