Im'試圖用最接近的可用RGB替換輸入圖像的所有像素。我有一個數組包含顏色和輸入圖像。這裏是我的代碼,它給我一個預期的輸出圖像,但它需要非常長的時間(大約一分鐘)來處理一個圖像。任何人都可以幫助我改進代碼嗎?或者如果您有任何其他建議,請幫助。如何優化這個圖像處理用最接近的可用RGB替換圖像上的所有像素?
UIGraphicsBeginImageContextWithOptions(CGSizeMake(CGImageGetWidth(sourceImage),CGImageGetHeight(sourceImage)), NO, 0.0f);
//Context size I keep as same as original input image size
//Otherwise, the output will be only a partial image
CGContextRef context;
context = UIGraphicsGetCurrentContext();
//This is for flipping up sidedown
CGContextTranslateCTM(context, 0, self.imageViewArea.image.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
// init vars
float d = 0; // squared error
int idx = 0; // index of palette color
int min = 1000000; // min difference
UIColor *oneRGB; // color at a pixel
UIColor *paletteRGB; // palette color
// visit each output color and determine closest color from palette
for(int y=0; y<sizeY; y++) {
for(int x=0; x<sizeX; x++) {
// desired (avg) color is one pixel of scaled image
oneRGB = [inputImgAvg colorAtPixel:CGPointMake(x,y)];
// find closest color match in palette: init idx with index
// of closest match; keep track of min to find idx
min = 1000000;
idx = 0;
CGContextDrawImage(context,CGRectMake(xx, yy, 1, 1),img);
}
}
UIImage *output = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.imageViewArea.image = output;
你的代碼的哪個部分需要最長的時間(循環,'UIGraphics'或'CGContext'函數等)?剖析你的代碼。 – Jacob 2012-02-13 15:23:44
'ColorDiff'的代碼是什麼?另外,慣例是用小寫字母初始化方法,例如:'[self colorDiffWithPalette:paletteRGB forRGB:oneRGB]' – zaph 2012-02-13 15:27:55
@Jacob:我認爲循環大部分時間都在使用中。 – user1139699 2012-02-13 15:47:01