You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将图像叠加到另一张图像上?实现随机区域图像遮挡

Julia Images库实现随机区域图像遮挡

问题描述

需要在图像的随机位置叠加指定尺寸的遮挡矩阵,原代码仅能替换图像左上角区域,现有代码如下:

using Images
        
add = "http://wonderfulengineering.com/wp-content/uploads/2014/04/ship-image-3.jpeg"
img =  load(download(add))
        
occlude = RMat = rand(RGB,100,250);
rowi = size(RMat,1)
coli = size(RMat,2)
        
for i in 1:rowi, j in 1:coli
    img[i,j] = RMat[i, j]
end

解决方案

核心是随机计算合法的遮挡区域起始坐标,再利用Julia的数组切片高效替换对应区域,无需手动循环。

完整实现代码

using Images, Random

# 加载目标图像
add = "http://wonderfulengineering.com/wp-content/uploads/2014/04/ship-image-3.jpeg"
img = load(download(add))

# 定义遮挡矩阵的尺寸并生成随机RGB矩阵
occlude_height, occlude_width = 100, 250
occlude_mat = rand(RGB, occlude_height, occlude_width)

# 获取图像的总行数和总列数
img_height, img_width = size(img)

# 计算合法的起始坐标范围,确保遮挡矩阵不超出图像边界
max_start_row = img_height - occlude_height + 1
max_start_col = img_width - occlude_width + 1

# 随机选择起始行和起始列
start_row = rand(1:max_start_row)
start_col = rand(1:max_start_col)

# 用遮挡矩阵替换图像对应区域(切片赋值更高效)
img[start_row:start_row+occlude_height-1, start_col:start_col+occlude_width-1] = occlude_mat

# 可选:保存处理后的图像
save("occluded_result.jpg", img)
# 或者直接显示图像
# display(img)

关键细节说明

  • 避免越界:通过img_height - occlude_height + 1计算最大合法起始行,保证遮挡矩阵的底部不会超出图像范围,列方向同理。
  • 高效赋值:Julia的数组切片赋值操作比手动循环快得多,是处理这类图像区域替换的最优方式。
  • 固定随机结果:如果需要重复相同的随机遮挡位置,可在代码开头添加Random.seed!(456)(数字可自定义)来固定随机种子。

内容的提问来源于stack exchange,提问作者Mike Computer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 18:45:22