将RGB转换为黑色或白色

时间:2013-09-13 03:34:52

标签: python opencv numpy python-imaging-library

如何在Python中拍摄RGB图像并将其转换为黑色或白色?不是灰度,我希望每个像素都是全黑(0,0,0)或全白(255,255,255)。

在流行的Python图像处理库中是否有任何内置功能?如果没有,那么最好的方法就是循环每个像素,如果它接近白色则将其设置为白色,如果它接近黑色则将其设置为黑色?

8 个答案:

答案 0 :(得分:81)

缩放为黑白

转换为灰度,然后缩放为白色或黑色(以最接近的为准)。

原件:

meow meow tied up cat

结果:

Black and white Cat, Pure

Pure Pillow实施

如果您还没有安装pillow

$ pip install pillow

Pillow(或PIL)可以帮助您有效地处理图像。

from PIL import Image

col = Image.open("cat-tied-icon.png")
gray = col.convert('L')
bw = gray.point(lambda x: 0 if x<128 else 255, '1')
bw.save("result_bw.png")

或者,您可以将Pillownumpy一起使用。

Pillow + Numpy Bitmasks Approach

你需要安装numpy:

$ pip install numpy

Numpy需要对数组进行操作,但结果是一样的。

from PIL import Image
import numpy as np

col = Image.open("cat-tied-icon.png")
gray = col.convert('L')

# Let numpy do the heavy lifting for converting pixels to pure black or white
bw = np.asarray(gray).copy()

# Pixel range is 0...255, 256/2 = 128
bw[bw < 128] = 0    # Black
bw[bw >= 128] = 255 # White

# Now we put it back in Pillow/PIL land
imfile = Image.fromarray(bw)
imfile.save("result_bw.png")

黑色和白色使用枕头,抖动

使用pillow,您可以将其直接转换为黑白。看起来它有灰色阴影,但你的大脑却在欺骗你! (彼此附近的黑色和白色看起来像灰色)

from PIL import Image 
image_file = Image.open("cat-tied-icon.png") # open colour image
image_file = image_file.convert('1') # convert image to black and white
image_file.save('/tmp/result.png')

原件:

meow meow color cat

转换:

meow meow black and white cat

黑色和白色使用枕头,没有抖动

from PIL import Image 
image_file = Image.open("cat-tied-icon.png") # open color image
image_file = image_file.convert('1', dither=Image.NONE) # convert image to black and white
image_file.save('/tmp/result.png')

答案 1 :(得分:4)

我建议转换为灰度,然后简单地应用一个阈值(中途,或平均值或meadian,如果你愿意的话)。

from PIL import Image

col = Image.open('myimage.jpg')
gry = col.convert('L')
grarray = np.asarray(gry)
bw = (grarray > grarray.mean())*255
imshow(bw)

答案 2 :(得分:2)

img_rgb = cv2.imread('image.jpg')
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
(threshi, img_bw) = cv2.threshold(img_gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)

答案 3 :(得分:1)

枕头,有抖动

使用pillow,您可以将其直接转换为黑白。看起来它有灰色阴影,但你的大脑却在欺骗你! (彼此附近的黑色和白色看起来像灰色)

from PIL import Image 
image_file = Image.open("cat-tied-icon.png") # open colour image
image_file = image_file.convert('1') # convert image to black and white
image_file.save('/tmp/result.png')

原件:

meow meow color cat

转换:

meow meow black and white cat

答案 4 :(得分:1)

您可以使用colorsys(在标准库中)将rgb转换为hls并使用亮度值来确定黑/白:

import colorsys
# convert rgb values from 0-255 to %
r = 120/255.0
g = 29/255.0
b = 200/255.0
h, l, s = colorsys.rgb_to_hls(r, g, b)
if l >= .5:
    # color is lighter
    result_rgb = (255, 255, 255)
elif l < .5:
    # color is darker
    result_rgb = (0,0,0)

答案 5 :(得分:0)

使用opencv您可以轻松地将rgb转换为二进制图像

import cv2
%matplotlib inline 
import matplotlib.pyplot as plt
from skimage import io
from PIL import Image
import numpy as np

img = io.imread('http://www.bogotobogo.com/Matlab/images/MATLAB_DEMO_IMAGES/football.jpg')
img = cv2.cvtColor(img, cv2.IMREAD_COLOR)
imR=img[:,:,0] #only taking gray channel
print(img.shape)
plt.imshow(imR, cmap=plt.get_cmap('gray'))

#Gray Image
plt.imshow(imR)
plt.title('my picture')
plt.show()

#Histogram Analyze

imgg=imR
hist = cv2.calcHist([imgg],[0],None,[256],[0,256])
plt.hist(imgg.ravel(),256,[0,256])

# show the plotting graph of an image

plt.show()

#Black And White
height,width=imgg.shape
for i in range(0,height):
  for j in range(0,width):
     if(imgg[i][j]>60):
        imgg[i][j]=255
     else:
        imgg[i][j]=0

plt.imshow(imgg)

答案 6 :(得分:0)

这是使用opencv-python创建二进制映像的代码:

img = cv2.imread('in.jpg',2)

ret, bw_img = cv2.threshold(img,127,255,cv2.THRESH_BINARY)

cv2.imshow("Output - Binary Image",bw_img)

答案 7 :(得分:0)

如果您不想使用cv方法进行分割并了解您在做什么,则将RGB图像视为矩阵。

image = mpimg.imread('image_example.png') # your image
R,G,B = image[:,:,0], image[:,:,1], image[:,:,2] # the 3 RGB channels
thresh = [100, 200, 50] # example of triple threshold

# First, create an array of 0's as default value
binary_output = np.zeros_like(R)
# then screen all pixels and change the array based on RGB threshold.
binary_output[(R < thresh[0]) & (G > thresh[1]) & (B < thresh[2])] = 255

结果是基于三元组条件的0和255的数组。