我有9张照片全部是一个人,但他正站在9张照片中的每张照片的不同位置。第一个嵌套for循环创建一个三重数组,其中j = picture,x和y表示每个图片中像素的坐标。我使用getpixel函数将它们存储在这个三重循环中。我的问题在于第二个嵌套的for循环。我为每个像素的rgb值创建一个数组,而不是对它们进行排序,以找到中间值。从理论上讲,这应该会返回一个图像,其中男人已经消失,而照片的背景仍然存在。然而,它不起作用,仍然显示与男子在其中的图片。我究竟做错了什么?
#include <iostream>
#include <stdlib.h>
#include <cmath>
#include <ctime>
#include <graphics.h>
#include <stdio.h>
using namespace std;
void loadImage(int imageNumber);
void bubbleSort(arr[], int n);
int main()
{
//triple array to work with all 9 pics
int picture[9][200][225];
int redArray[9];
int greenArray[9];
int blueArray[9];
//size of the 3 arrays to be used in bubble sort
int n1=sizeof(redArray);
int n2=sizeof(greenArray);
int n3=sizeof(blueArray);
//window that displays the picture
initwindow(600, 625, "tourist");
//stores the pixel value for all 9 pictures
for(int j=0; j<9; j++)
{
loadImage(j);
{
for(int x=0; x<200; x++)
{
for(int y=0; y<225; y++)
{
picture[j][x][y]=getpixel(x, y);
}
}
}
}
//sets the rgb values of all the pixels of all the pictures and bubble sorts them
//using the median value of 9 elements(4th value) to remove the person from the picture
for(int x=0; x<200; x++)
{
for(int y=0; y<225; y++)
{
for(int j=0; j<9; j++)
{
redArray[j]=RED_VALUE(picture[j][x][y]);
greenArray[j]=GREEN_VALUE(picture[j][x][y]);
blueArray[j]=BLUE_VALUE(picture[j][x][y]);
}
bubbleSort(redArray[], n1);
bubbleSort(greenArray[], n2);
bubbleSort(blueArray[], n3);
//putpixel redarray[4]
putpixel(x,y,Color(redArray[4], greenArray[4], blueArray[4]);
}
}
getch();
}
//this is a BGI function that loads the image onto the current window
void loadImage(int imageNumber)
{
char str[5];
sprintf(str, "%i.jpg", imageNumber);
readimagefile(str,0,0,200,225);
}
void bubbleSort(int arr[], int n)
{
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n - i - 1; ++j)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
答案 0 :(得分:1)
这一行
int n1=sizeof(redArray);
将n1设置为9个整数的大小,大概为36(取决于您的机器架构)
然后,您将此作为冒泡排序的输入,这意味着您的冒泡排序将超出数组边界。这是未定义的行为,可能导致数组中的值不正确。
将行更改为
int n1=sizeof(redArray) / sizeof (redArray[0]);
或者甚至只是在其他几个地方使用9
(也许您可以将const int
定义为9,以便日后轻松更改。