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;
}

改动说明

  1. 确保 ( w ) 和 ( h ) 是 2 的倍数:

    • 使用 (rand() % (maxWidth / 2) + 1) * 2 生成宽度,确保生成的值范围是 ( [2, \text{maxWidth}] ),且是偶数。
    • 类似地,使用 (rand() % (maxHeight / 2) + 1) * 2 生成高度。
  2. 保持边界校验:

    • ( x ) 和 ( y ) 的计算不受影响,仍然确保裁剪框在图像范围内。

输出示例

每次运行程序将输出不同的裁剪尺寸,且 ( w ) 和 ( h ) 必定是 2 的倍数。例如:

Random Crop Rectangle:
x: 12, y: 30, w: 128, h: 64

此修改确保宽度和高度符合要求,并且裁剪框始终位于有效范围内。

 
posted @   海_纳百川  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
本站总访问量8979599
 
点击右上角即可分享
微信分享提示