华为OD机试 - 灰度图存储(Java & JS & Python & C & C++)
题目描述:
给定一个代表图像的二维整数数组,其中的整数代表颜色值,要求设计一个算法,将该图像转换为灰度图像。
解法1:Java版本
public class Solution {
public int[][] toGrayImage(int[][] image) {
int rows = image.length, cols = image[0].length;
int[][] grayImage = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
int originalColor = image[i][j];
// 转换为灰度值的公式为: gray = 0.3*R + 0.59*G + 0.11*B
int gray = (int) (0.3 * ((originalColor >> 16) & 0xff) +
0.59 * ((originalColor >> 8) & 0xff) +
0.11 * (originalColor & 0xff));
grayImage[i][j] = (originalColor & 0xff000000) | (gray << 16) | (gray << 8) | gray;
}
}
return grayImage;
}
}
解法2:JavaScript版本
function toGrayImage(image) {
let grayImage = image.map(row => {
return row.map(color => {
let r = (color >> 16) & 255;
let g = (color >> 8) & 255;
let b = color & 255;
let gray = Math.floor(0.3 * r + 0.59 * g + 0.11 * b);
return (color & 0xff000000) | (gray << 16) | (gray << 8) | gray;
});
});
return grayImage;
}
解法3:Python版本
def to_gray_image(image):
gray_image = [[int(((color >> 16) & 0xff) * 0.3 +
((color >> 8) & 0xff) * 0.59 +
(color & 0xff) * 0.11) for color in row] for row in image]
return [[(color << 16) | (color << 8) | color | (color >> 24) << 24 for color in row] for row in gray_image]
解法4:C语言版本
#include <stdint.h>
void toGrayImage(int **image, int rows, int *cols, int ***grayImage) {
*grayImage = (int **) malloc(sizeof(int *) * rows);
for (int i = 0; i < rows; i++) {
(*grayImage)[i] = (int *) malloc(sizeof(int) * (*cols));
for (int j = 0; j < *cols; j++) {
int originalColor = image[i][j];
int gray = (int) (0.3 * (((originalColor >> 16) & 0xff
评论已关闭