【发布时间】:2017-05-12 19:23:52
【问题描述】:
总的来说:如何更有效地实现和使用遍历偏移量?
假设我们在下面定义了一个位图。我们如何从一个固定像素开始遍历(在这种情况下收集)所有附近的像素 - 并最终避免这 8 个 if 语句?
// The bitmap 1920x1080px
RGBColor[][] imageMatrix = new RGBColor[1920][1080];
// Collect all nearby pixels that are not white
ArrayList<RGBColor> neighboringPixels = new ArrayList<RGBColor>();
// Width-index of center pixel
int w = 50;
// Height-index of center pixel
int h = 50;
// Initializing offsets for a more elegant check-up...
int[][] offsets = { { -1, -1 }, { 0, -1 }, { 1, -1 },
{ 1, 0 }, { 1, 1 }, { 0, 1 }, { -1, 1 },
{ -1, 0 } };
// But this is what I came up with
// Get top-left pixel
if (!(w - 1 < 0 || w - 1 > 255 || h - 1 < 0 || h - 1 > 255)) {
neighboringPixels.add(imageMatrix[w - 1][h - 1]);
}
// Get top pixel
if (!(w < 0 || w > 255 || h - 1 < 0 || h - 1 > 255)) {
neighboringPixels.add(imageMatrix[w][h - 1]);
}
// Get top-right pixel
if (!(w + 1 < 0 || w + 1 > 255 || h - 1 < 0 || h - 1 > 255)) {
neighboringPixels.add(imageMatrix[w + 1][h - 1]);
}
// Get right pixel
if (!(w + 1 < 0 || w + 1 > 255 || h < 0 || h > 255)) {
neighboringPixels.add(imageMatrix[w + 1][h]);
}
// Get bottom-right pixel
if (!(w + 1 < 0 || w + 1 > 255 || h + 1 < 0 || h + 1 > 255)) {
neighboringPixels.add(imageMatrix[w + 1][h + 1]);
}
// Get bottom pixel
if (!(w < 0 || w > 255 || h + 1 < 0 || h + 1 > 255)) {
neighboringPixels.add(imageMatrix[w][h + 1]);
}
// Get bottom-left pixel
if (!(w - 1 < 0 || w - 1 > 255 || h + 1 < 0 || h + 1 > 255)) {
neighboringPixels.add(imageMatrix[w - 1][h + 1]);
}
// Get left pixel
if (!(w - 1 < 0 || w - 1 > 255 || h < 0 || h > 255)) {
neighboringPixels.add(imageMatrix[w - 1][h]);
}
【问题讨论】:
-
定义“高效”?你是说速度还是代码行数?
-
@Lashane 我主要是指代码行。如果我们在三维空间中工作,必须有一种方法可以避免这 8 个 if 语句甚至 26 个 if 语句。
标签: java arrays bitmap offset traversal