gpt4 book ai didi

c++ - 通过标准平均 C++ 模糊图像

转载 作者:行者123 更新时间:2023-11-28 07:10:50 27 4
gpt4 key购买 nike

我试图在不使用 opencv 预定义函数(如 blur())的情况下模糊图像。我使用的是标准平均值而不是加权平均值。这是我的代码,但结果仍然与输入图像相同。这是 3x3 的。

    IplImage* img = cvLoadImage(argv[1]);
IplImage* dst = cvCloneImage(img);

height = img->height;
width = img->width;
step = img->widthStep;
channels = img->nChannels;
data = (uchar *)img->imageData;

height2 = dst->height; // row
width2 = dst->width; // col
step2 = dst->widthStep; // size of aligned image row in bytes
channels2 = dst->nChannels;
dstData = (uchar *)dst->imageData;
int total = 0;

//blur
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
for (x = 0; x <= 2; x++)
for (y = 0; y <= 2; y++)
total =(data[x-1,y-1]+data[x-1,y]+data[x-1,y+1]+
data[x,y-1]+data[x,y]+data[x,y+1]+
data[x+1,y-1]+data[x+1,y]+data[x+1,y+1])/9;
dstData[i,j] = total;
}
}

我想我的问题出在这个上

                       total =(data[x-1,y-1]+data[x-1,y]+data[x-1,y+1]+
data[x,y-1]+data[x,y]+data[x,y+1]+
data[x+1,y-1]+data[x+1,y]+data[x+1,y+1])/9;
dstData[i,j] = total;

可以做什么?

最佳答案

一个完整的程序,展示了如何做到这一点。你有几个错误,1)不正确的像素访问(http://www.comp.leeds.ac.uk/vision/opencv/iplimage.html)。 2) 模糊循环是错误的,你总是从左上角的 3x3 角获取数据。如果像素访问正确,你应该在 dst 中得到一个恒定的图像。

另一件事是您还需要处理 channel 信息,程序通过读取单个 channel 图像来绕过它。否则你需要为每个 channel 做模糊

#include <opencv2/opencv.hpp>


int main(int argc, char* argv[])
{

IplImage* img = cvLoadImage("c:/data/2.jpg",0);
IplImage* dst = cvCloneImage(img);
int height,width,step,channels;
int height2,width2,step2,channels2;

height = img->height;
width = img->width;
step = img->widthStep;
channels = img->nChannels;
uchar* data = (uchar *)img->imageData;

height2 = dst->height; // row
width2 = dst->width; // col
step2 = dst->widthStep; // size of aligned image row in bytes
channels2 = dst->nChannels;
uchar* dstData = (uchar *)dst->imageData;
int total = 0;
int i,j,x,y,tx,ty;
//blur
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
int ksize=3;
total=0;
for (x = -ksize/2; x <=ksize/2; x++)
for (y = -ksize/2; y <=ksize/2; y++)
{
tx=i+x;
ty=j+y;
if(tx>=0&&tx<height && ty>=0 && ty<width)
{
total+=data[tx*step+ty];
}
}

dstData[i*step+j] = total/ksize/ksize;
}
}
cvShowImage("img",img);
cvShowImage("dst",dst);
cvWaitKey(0);
}

关于c++ - 通过标准平均 C++ 模糊图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20999555/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com