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

如何为图像添加条纹噪声?(Matlab代码问题及多语言实现)

图像添加固定间隔条纹噪声的多语言实现方案

问题描述

需要为图像添加固定像素间隔的条纹噪声(每3行添加1行黑条纹),原Matlab代码尝试将生成的条纹图与原图相加,结果得到白色条纹而非预期黑条纹——原因是黑条纹的0像素被原图像素覆盖,需修正实现逻辑,并获取Matlab、Python、C++三种语言的可行方案。

原Matlab代码:

for i = 1:512
    counter = counter + 1;
    if counter > 3
        counter = 0;
    end
    for j = 1:512
        if counter < 3
            img{i,j} = 255;
        elseif counter == 3
            img{i,j} = 0;
        end
    end
end

fr = imread("image.bmp")

sum = fr + img;

Matlab 实现方案

核心问题在于相加操作错误:黑条纹需要直接覆盖原图对应行,而非相加;同时原代码误用细胞数组{}存储图像,需改为普通矩阵,且要匹配原图的维度与数据类型。

修正后的代码:

% 读取图像,自动适配灰度/彩色图
fr = imread("image.bmp");
[h, w, c] = size(fr);

% 生成条纹掩码:每3行保留原图,第4行设为黑(0)
mask = ones(h, w, c, class(fr)); % 初始化与原图同类型的全1掩码
mask(4:4:h, :, :) = 0; % 第4、8、12...行设为0,若要第3行黑则改为3:4:h

% 应用掩码:直接相乘实现覆盖,保留行乘1不变,黑条纹行乘0置黑
noisy_img = fr .* mask;

% 显示结果
imshow(noisy_img);

Python 实现方案

基于OpenCV的实现

import cv2
import numpy as np

# 读取图像
img = cv2.imread("image.bmp")
if img is None:
    raise ValueError("无法读取图像文件")
h, w, c = img.shape

# 生成掩码
mask = np.ones((h, w, c), dtype=img.dtype)
mask[4:4:h, :, :] = 0  # 第4、8...行设为0,索引规则同Matlab

# 应用掩码生成带噪声图像
noisy_img = img * mask

# 显示与保存
cv2.imshow("Noisy Image", noisy_img)
cv2.waitKey(0)
cv2.imwrite("noisy_image.bmp", noisy_img)

基于PIL的实现

from PIL import Image
import numpy as np

# 读取图像
img = Image.open("image.bmp")
img_np = np.array(img)
h, w = img_np.shape[:2]

# 生成掩码
mask = np.ones_like(img_np)
mask[4:4:h, :] = 0

# 应用掩码并转成图像格式
noisy_img_np = img_np * mask
noisy_img = Image.fromarray(noisy_img_np)

# 显示与保存
noisy_img.show()
noisy_img.save("noisy_image.bmp")

C++ 实现方案

基于OpenCV库实现,注意C++图像索引从0开始:

#include <opencv2/opencv.hpp>
using namespace cv;

int main() {
    // 读取图像
    Mat img = imread("image.bmp");
    if (img.empty()) {
        printf("无法读取图像文件\n");
        return -1;
    }
    
    int h = img.rows;
    int channel = img.channels();
    
    // 生成掩码
    Mat mask = Mat::ones(h, img.cols, img.type());
    // C++索引从0开始,第4行对应i=3,每4行循环一次
    for (int i = 3; i < h; i += 4) {
        if (channel == 3) {
            mask.row(i) = Scalar(0, 0, 0); // 彩色图置黑
        } else {
            mask.row(i) = Scalar(0); // 灰度图置黑
        }
    }
    
    // 应用掩码
    Mat noisy_img;
    multiply(img, mask, noisy_img);
    
    // 显示与保存
    imshow("Noisy Image", noisy_img);
    waitKey(0);
    imwrite("noisy_image.bmp", noisy_img);
    
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 03:55:25