[英]What's the best way of changing the 24 pixels around a particular pixel?
我目前正在研究一段代碼,該代碼可以更改圖像某些像素的顏色。 它通過以下方法執行此操作:
inputImage.put(25, 25, colour);
這將在x坐標25, y坐標25處選擇一個像素,然后將其更改為指定的color 。
現在,我必須將此像素及其周圍的24個像素更改為新顏色,這意味着有5x5的空間會重新着色。
我可以想到幾種方法。 一種方法是遍歷圖像的所有像素,並檢查x和y坐標是否在23到27之間,然后重新着色。 另一個是單獨指定需要更改的每個像素。 但是,這兩個想法似乎有點松弛。 有人可以推薦一種更優雅的方式嗎?
不要循環。
而是設置完整的5x5 roi(在x,y處):
int x=15,y=7;
in.submat(y-3,y+2, x-3,x+2).setTo(colour);
也許將循環條件更改為從特定的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);
}
}
正確的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());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.