![](/img/trans.png)
[英]How to convert a python numpy array to an RGB image with Opencv 2.4?
[英]How can i get the RGB values of an image as numpy array using OpenCV, Python
我需要使用 OpenCV 对图像的 RGB 值,但是当我读取如下图像时,有时它不会返回精确值。
import cv2
img = cv2.imread('camel.jpeg')
例如
对于这张图片( camel.jpg ),一切都是正确的,但对于这张图片( result.jpg ),它为每个像素返回 255。 但如果尝试读取特定像素,我可以达到像素的 RGB 值。 我尝试使用 for 循环,但结果不正确,它再次为每个像素返回 255。 我应该怎么办?
我在 Python/OpenCV 中对您的骆驼图像执行此操作以获得两个像素。 通道值不仅仅是 0 和 255。
import cv2
import numpy as np
# load image and get dimensions
img = cv2.imread("camel.jpg")
hh, ww = img.shape[:2]
# get pixel at x=0,y=0
px1 = img[0:1, 0:1]
# get pixel at center of image
hh2 = hh//2
ww2 = ww//2
px2 = img[hh2:hh2+1, ww2:ww2+1]
print(px1)
print(px2)
结果:
[[[0 0 0]]]
[[[129 0 193]]]
但是您应该能够只print(img)
或使用 Numpy 裁剪区域并打印它。
也许您的 camel.jpeg 图像有问题,但在保存和发布时它会得到修复。 尝试上传您发布的文件,看看它是否有同样的问题。
我为此使用了 Pillow,效果非常好
from PIL import Image
import numpy as np
img = Image.open('camel.jpeg')
img_array = np.array(img)
print(img_array.shape)
print(img_array)
结果
(1477, 1200, 3)
[[[105 159 206]
[106 160 207]
[106 160 207]
...
[215 215 217]
[215 215 217]
[216 216 218]]
[[105 159 206]
[106 160 207]
[106 160 207]
...
它工作正常,你可以说img_array
的形状也与camel.jpeg
的分辨率相匹配
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.