C++生成随机裁剪尺寸
随机裁剪尺寸 (x, y, w, h)
,其中裁剪区域的宽度和高度不能超过 640 和 360,保证裁剪的宽度和高度 ( w ) 和 ( h ) 是 2 的倍数
代码
#include <iostream>
#include <cstdlib> // For rand() and srand()
#include <ctime> // For time()
struct CropRect {
int x; // Top-left x-coordinate
int y; // Top-left y-coordinate
int w; // Width of the crop
int h; // Height of the crop
};
CropRect generateRandomCrop(int maxWidth, int maxHeight) {
CropRect rect;
// Generate random width and height as multiples of 2
rect.w = (rand() % (maxWidth / 2) + 1) * 2; // Width: 2 to maxWidth, step 2
rect.h = (rand() % (maxHeight / 2) + 1) * 2; // Height: 2 to maxHeight, step 2
// Generate random top-left corner ensuring it fits within the boundaries
rect.x = rand() % (maxWidth - rect.w + 1); // x: 0 to (maxWidth - width)
rect.y = rand() % (maxHeight - rect.h + 1); // y: 0 to (maxHeight - height)
return rect;
}
int main() {
// Set seed for random number generation
srand(static_cast<unsigned>(time(0)));
int maxWidth = 640; // Maximum width
int maxHeight = 360; // Maximum height
CropRect crop = generateRandomCrop(maxWidth, maxHeight);
std::cout << "Random Crop Rectangle:" << std::endl;
std::cout << "x: " << crop.x << ", y: " << crop.y << ", w: " << crop.w << ", h: " << crop.h << std::endl;
return 0;
}
改动说明
-
确保 ( w ) 和 ( h ) 是 2 的倍数:
- 使用
(rand() % (maxWidth / 2) + 1) * 2
生成宽度,确保生成的值范围是 ( [2, \text{maxWidth}] ),且是偶数。 - 类似地,使用
(rand() % (maxHeight / 2) + 1) * 2
生成高度。
- 使用
-
保持边界校验:
- ( x ) 和 ( y ) 的计算不受影响,仍然确保裁剪框在图像范围内。
输出示例
每次运行程序将输出不同的裁剪尺寸,且 ( w ) 和 ( h ) 必定是 2 的倍数。例如:
Random Crop Rectangle:
x: 12, y: 30, w: 128, h: 64
此修改确保宽度和高度符合要求,并且裁剪框始终位于有效范围内。
本文来自博客园,作者:海_纳百川,转载请注明原文链接:https://www.cnblogs.com/chentiao/p/18637418,如有侵权联系删除
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义