将8位转换为4位图像

时间:2015-10-14 11:23:49

标签: java image grayscale

当我尝试将8位图像转换为4位图像时,有谁可以看到问题是什么?

我正在测试使用此处的8位图像:http://laurashoe.com/2011/08/09/8-versus-16-bit-what-does-it-really-mean/

你可以看出4位图像应该是什么样子,但我的几乎是纯黑色。

        // get color of the image and convert to grayscale
        for(int x = 0; x <img.getWidth(); x++) {
            for(int y = 0; y < img.getHeight(); y++) {
                int rgb = img.getRGB(x, y);
                int r = (rgb >> 16) & 0xF;
                int g = (rgb >> 8) & 0xF;
                int b = (rgb & 0xF);

                int grayLevel = (int) (0.299*r+0.587*g+0.114*b);
                int gray = (grayLevel << 16) + (grayLevel << 8) + grayLevel;
                img.setRGB(x,y,gray);
            }
        }

3 个答案:

答案 0 :(得分:0)

你应该使用0xFF而不是0xF,因为0xF意味着只有最后四位,wchich几乎不会告诉你颜色,因为在RGB中颜色是8位。

尝试这项工作:

 // get color of the image and convert to grayscale
        for(int x = 0; x <img.getWidth(); x++) {
            for(int y = 0; y < img.getHeight(); y++) {
                int rgb = img.getRGB(x, y);
                int r = (rgb >> 16) & 0xFF;
                int g = (rgb >> 8) & 0xFF;
                int b = (rgb & 0xFF);

                int grayLevel = (int) (0.299*r+0.587*g+0.114*b);
                int gray = (grayLevel << 16) + (grayLevel << 8) + grayLevel;
                img.setRGB(x,y,gray);
            }
        }

答案 1 :(得分:0)

由于代码已经从问题中删除了,所以这里是来自评论的确认解决方案:

// get color of the image and convert to grayscale
for(int x = 0; x <img.getWidth(); x++) {
    for(int y = 0; y < img.getHeight(); y++) {
        int rgb = img.getRGB(x, y);

        // get the upper 4 bits from each color component
        int r = (rgb >> 20) & 0xF;
        int g = (rgb >> 12) & 0xF;
        int b = (rgb >> 4) & 0xF;

        int grayLevel = (int) (0.299*r+0.587*g+0.114*b);

        // use grayLevel value as the upper 4 bits of each color component of the new color
        int gray = (grayLevel << 20) + (grayLevel << 12) + (grayLevel << 4);
        img.setRGB(x,y,gray);
    }
}

请注意,生成的图像看起来只有4位灰度,但仍然使用int作为RGB值。

答案 2 :(得分:0)

8 位图像值在 [0, 255] 范围内,因为 pow(2, 8) = 256

要获得范围为 [0, 15] 的 4 位图像值,pow(2, 4) = 16, 我们需要将每个像素值除以 16 -> 范围 [0, 255] / 16 = 范围 [0, 15]。

import cv2
import numpy as np
import matplotlib.pyplot as plt

img = cv2.imread("crowd.jpeg")
#Convert the image to grayscale
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
plt.imshow(gray_img, cmap='gray')

Grayscale image

bit_4 = np.divide(gray_img, 16).astype('uint8')
plt.imshow(bit_4, cmap='gray')

Bit4 image