我目前正在研究一段代码,它可以改变图像中某些像素的颜色。它通过以下方法进行此操作:
inputImage.put(25, 25, colour);这将在x坐标25,y坐标25处选择一个像素,然后将其更改为指定的颜色。
我现在必须改变这个像素和它周围的24个像素到一个新的颜色,这意味着有一个5x5的空间被重新着色。
我可以想出几种方法来做到这一点。一种方法是迭代图像的所有像素,并检查它们是否在x和y坐标的23到27之间,然后对它们重新着色。另一种是单独指定需要更改的每个像素。但这两种想法似乎都有些松懈。有人能推荐一种更优雅的方法吗?
发布于 2015-02-02 15:42:50
别绕圈。
相反,设置完整的5x5roi(在x,y处):
int x=15,y=7;
in.submat(y-3,y+2, x-3,x+2).setTo(colour);发布于 2015-02-02 15:28:18
可能会将循环条件更改为从特定的x和y开始,在边界处结束(可能是x+5和y+5)。
示例:
int start = 23;
int boundary = start+5;
for(int x = start; x < boundary; x++) {
for(int y = start; y < boundary; y++) {
inputImage.put(x,y,colour);
}
}发布于 2015-02-02 15:54:12
一个正确的oop解决方案是定义一个Point类并创建一个Iterator来遍历您想要的范围。
class Point {
public static final Point UNIT = new Point(1, 1);
public static final Point X = new Point(1, 0);
public static final Point Y = new Point(0, 1);
public static final Point ZERO = new Point(0, 0);
final int x;
final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public Point(Point from) {
this(from.x, from.y);
}
public Point add(Point delta) {
return new Point(x + delta.x, y + delta.y);
}
public Point sub(Point delta) {
return add(delta.negate());
}
public Point negate() {
return new Point(-x, -y);
}
public String toString() {
return "[" + x + "," + y + "]";
}
}
class Around implements Iterator<Point> {
private final Point center;
private final Point range;
private Point last = null;
private Point next = null;
public Around(Point center, Point range) {
this.center = center;
this.range = range;
}
@Override
public boolean hasNext() {
if (next == null) {
if (last != null) {
// Are we still in vertical range.
if (last.y <= center.y + range.y) {
// Next is last step right one.
next = last.add(Point.X);
// Have we hit limit?
if (next.x > center.x + range.x) {
next = next.add(new Point((-2 * range.x) - 1, 1));
if (next.y >= center.y + range.y + 1) {
// Fallen out of y range.
next = null;
}
}
}
} else {
// First = center - range.
last = center.add(range.negate());
next = last;
}
}
return next != null;
}
@Override
public Point next() {
Point n = last = next;
next = null;
return n;
}
}
public void test() {
Iterator<Point> around = new Around(new Point(0, 0), new Point(2, 2));
while (around.hasNext()) {
System.out.println(around.next());
}
}https://stackoverflow.com/questions/28280970
复制相似问题