我正在开发一个小程序,可以在不同的视频模式下绘制矩形(例如1920 x 1080-> 640 x 480)。我可以调整矩形的大小。但是我被困住了,因为我找不到解决问题的明确方法。我目前正在尝试创建一个矩阵以对像素执行缩放操作,但无法获得正确的答案。问题的一部分似乎TransformMatrix::transform
是缩放比例不正确。
#include <iostream>
typedef struct _Pixel
{
_Pixel():X(1920)
,Y(1080)
{}
unsigned X;
unsigned Y;
}Pixel;
typedef struct TransformMatrix
{
constexpr TransformMatrix(const float aWeigth = 0.3f
,const float aHeigth = 0.225f):W(aWeigth)
,H(aHeigth)
{}
void transform( const Pixel & aPixel)
{
auto x_value=static_cast<float>(aPixel.X)*W;
auto y_value=static_cast<float>(aPixel.Y)*H;
std::cout<<"x_value: "<<x_value<<std::endl;
std::cout<<"y_value: "<<y_value<<std::endl;
}
const float W;
const float H;
}TransformMatrix;
int main()
{
Pixel aPixel;
TransformMatrix _TransformMatrix;
_TransformMatrix.transform(aPixel);
return 0;
}
实际结果:
x值:576
y值:243
预期结果:
x值:640
y值:480
如何执行正确的操作?只是在改变基础吗?我应该只扩展还是进行转换操作?
哇,既然有人督促我,让我在这里解释最重要的风格改进:
C
从C ++ 98开始,它们就已经成为C和过时的东西了operator<<
用于iostream)纯函数:maketransform
返回修改后的值,而不是对参数进行突变。通常,这使代码更安全,并且可以启用一类优化。在极少数情况下,您想要就地更新像素,只需编写
pixel = transform(pixel); // the optimizer will see right through this
创建TransformMatrix
一个可调用对象(通过代替transform
asoperator()
来实现。这样,您可以简单地将其用作函数,例如在算法中:
std::vector<Pixel> poly1, poly2;
std::transform(poly1.begin(), poly1.end(),
back_inserter(poly2), TransformMatrix());
只需将poly1中的所有像素转换为poly2。
读者的练习:按其名称TransformMatrix
说的做。现在,它更像ScalePixel
#include <iostream>
struct Pixel {
Pixel(unsigned x = 1920, unsigned y = 1080) : X(x), Y(y) {}
unsigned X;
unsigned Y;
friend std::ostream& operator<<(std::ostream& os, Pixel const& p) {
return os << "Pixel(" << p.X << ", " << p.Y << ")";
}
};
struct TransformMatrix {
constexpr TransformMatrix(float aWidth = 640/1920.f, float aHeigth = 480/1080.f) : W(aWidth), H(aHeigth) {}
Pixel operator()(const Pixel &aPixel) const {
return { static_cast<unsigned>(aPixel.X * W), static_cast<unsigned>(aPixel.Y * H) };
}
float W;
float H;
};
int main() {
Pixel aPixel;
TransformMatrix xfrm;
std::cout << aPixel << " -> " << xfrm(aPixel) << "\n";
}
印刷:
Pixel(1920, 1080) -> Pixel(640, 480)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句