从图像中获取颜色并表示颜色

时间:2019-01-27 15:30:14

标签: python python-3.x opencv

我想知道X颜色是否出现在图像中。在这种情况下,研究的颜色将为绿色,因此其RGB值为(0.255.0)。

我应用以下代码:

img = cv2.imread('img.jpg')

L1 = [0, 255, 0]

matches = np.all(img == L1, axis=2)
result = np.zeros_like(img)

print(result.any())
result[matches] = [255, 0, 255]

cv2.imwrite('resultado.jpg', result)

基本上:

  1. 我加载要分析的图像。
  2. 我描述了我想要获得的RGB值。
  3. 我检查该颜色(绿色)是否出现在图像中。
  4. 我创建了一个我的尺寸完全为黑色的图像,并将其命名为 “结果”。
  5. 如果该颜色通过布尔值显示,则会在屏幕上显示。
  6. 结果我画了红色的绿色区域。
  7. 最后我要走最后一步。

下面显示的是工作室图像,然后显示为红色。

Image to study

Result

为什么一个盒子的漆成红色而不是绿色?为什么只是这些小点?

谢谢!

3 个答案:

答案 0 :(得分:1)

问题是由绿色区域引起的,并不是像您认为的那样,[0, 255, 0]只是您输入的图像,而是从OT21t.jpg构建的,

import cv2
img = cv2.imread('OT21t.jpg')
print(img[950,1300])

我得到了[ 2 255 1],所以不是[0,255,0]。请记住,保存.jpg图像时,通常是有损过程-可能会抛弃部分数据,从而允许文件较小(有关搜索lossy compression的更多信息)。

答案 1 :(得分:1)

这是一个可以满足您需求的脚本,我也使用了numpy,因此适应您的需求并不困难。

此脚本将找到一种颜色,并替换为另一种颜色:

import numpy
from PIL import Image
im = numpy.array(Image.open("/path/to/img.jpg"))

tol = 4     # tolerence (0 if you want an exact match) 
target_color = [0, 255, 0, 255]  # color to change
replace_color = [255, 0, 255, 255]  # color to use to paint the zone
for y, line in enumerate(im):
    for x, px in enumerate(line):
        if all((abs(px[i] - target_color[i]) < tol for i in range(3))):
            im[y][x] = replace_color
Image.fromarray(im).save("./Desktop/img.png")

这是黑色,只有火柴用替换色上色:

import numpy
from PIL import Image
im = numpy.array(Image.open("/path/to/img.jpg"))
new_im = numpy.zeros_like(im)

tol = 4     # tolerence (0 if you want an exact match) 
target_color = [0, 255, 0, 255]  # color to change
replace_color = [255, 0, 255, 255]  # color to use to paint the zone
for y, line in enumerate(im):
    for x, px in enumerate(line):
        if all((abs(px[i] - target_color[i]) < tol for i in range(3))):
            new_im[y][x] = replace_color
Image.fromarray(new_im).save("./Desktop/img.png")

脚本中缺少的是一些容忍度,因为您的绿色可能不是完美的绿色。

答案 2 :(得分:1)

我通常更适合使用“色相,饱和度和亮度” 系统而不是RGB来分离图像中的颜色-请参阅Wikipedia article here

因此,您可能会考虑以下内容:

#!/usr/local/bin/python3
import numpy as np
from PIL import Image

# Open image and make RGB and HSV versions
RGBim = Image.open("seaside.jpg")
HSVim = RGBim.convert('HSV')

# Make numpy versions
RGBna = np.array(RGBim)
HSVna = np.array(HSVim)

# Extract Hue
H = HSVna[:,:,0]

# Find all green pixels, i.e. where 110 < Hue < 130
lo,hi = 110,130
# Rescale to 0-255, rather than 0-360 because we are using uint8
lo = int((lo * 255) / 360)
hi = int((hi * 255) / 360)
green = np.where((H>lo) & (H<hi))

# Make all green pixels red in original image
RGBna[green] = [255,0,0]

count = green[0].size
print("Pixels matched: {}".format(count))
Image.fromarray(RGBna).save('result.png')

enter image description here

相关问题