如何调整彩色图像的灰度图像算法?

时间:2017-03-22 16:45:59

标签: python image-processing

我一直在使用https://gist.github.com/chsasank/4d8f68caf01f041a6453e67fb30f8f5a进行图像处理。这需要一个只有一个通道的图像(参见<canvas id="canvas" width=500 height=500 style="display: block; border: 1px solid green; margin: auto;"></canvas> <script> var ctx = document.getElementById('canvas').getContext('2d'); ctx.font = '30px Arial'; var HEIGHT = 500; var WIDTH = 500; var SEGMENT_WIDTH = 30; var snakeVelocity = { i: 1, j: 0 }; var snakeArray = createSnake(); function createSnake() { var snakeArray = []; var length = 5; // Initial length of snake for (var i = 0; i < length; i++) { snakeArray.push({ x: i + 1, y: 1 }); } return snakeArray; } function moveSnake(arr) { var head = arr.slice(-1)[0]; var tail = arr[0]; var newHead = arr.shift(); // check for wall collision, which also updates velocity if needed snakeWallCollision(head); newHead.x = head.x + snakeVelocity.i; newHead.y = head.y + + snakeVelocity.j; arr.push(newHead); return arr; } function snakeWallCollision(obj) { var collision = false; if (obj.x >= WIDTH / SEGMENT_WIDTH || obj.x <= 0) { snakeVelocity.i *= -1; collision = true; } if (obj.y >= HEIGHT / SEGMENT_WIDTH || obj.y <= 0) { snakeVelocity.j *= -1; collision = true; } return collision; } function drawSnake() { console.log(snakeArray[0]); for (var i = 0; i < snakeArray.length; i++) { var segment = snakeArray[i]; ctx.fillText('S', segment.x * SEGMENT_WIDTH, segment.y * SEGMENT_WIDTH + 30); } } function update() { ctx.clearRect(0, 0, WIDTH, HEIGHT); moveSnake(snakeArray); drawSnake(); } function checkKey(e) { e = e || window.event; if ([38, 40, 37, 39].includes(e.keyCode)) { e.preventDefault(); } if (e.keyCode == '38') { snakeVelocity = { i: 0, j: -1 }; } else if (e.keyCode == '40') { snakeVelocity = { i: 0, j: 1 }; } else if (e.keyCode == '37') { snakeVelocity = { i: -1, j: 0 }; } else if (e.keyCode == '39') { snakeVelocity = { i: 1, j: 0 }; } } document.onkeydown = checkKey; setInterval(update, 1000 / 20); drawSnake(); </script> )如何调整代码以使其适用于彩色图像 - 所以图像有三个通道?

1 个答案:

答案 0 :(得分:1)

最简单的方法是将图像分割成通道,然后在重新映射后,将它们合并在一起。

# make sure it's not gray
assert len(image.shape) == 3

# grab the image resolution
shape = image.shape[:2]

# random_state, gaussian and meshgrid
.
.
.

#calculate indices just as before
indices = np.reshape(x+dx, (-1, 1)), np.reshape(y+dy, (-1, 1))

# split the image into 3 channels
b, g, r = cv2.split(image)

# do the mapping on all of the channels separately
b = map_coordinates(b, indices, order=1).reshape(shape)
g = map_coordinates(g, indices, order=1).reshape(shape)
r = map_coordinates(r, indices, order=1).reshape(shape)

# return merged result
return cv2.merge((b,g,r))