简体   繁体   English

使用python接口快速处理opencv图像像素

[英]processing opencv image pixels quickly using python interface

Using python-interface for OpenCV, one can easily access the pixel of image using [] operator,like this: 使用python-interface for OpenCV,可以使用[]运算符轻松访问图像像素,如下所示:

img = cv.LoadImage('test.jpg')
pixel = img[10,10]

variable pixel here is a python tuple object like (10,20,30) (3 channels for example), it's not very convenient to process computation since tuple type does not support operator '-' or '+' . 这里的变量像素是一个python元组对象,如(10,20,30) (例如3个通道),处理计算不是很方便,因为元组类型不支持运算符' - '或'+' If I hope to do a substruction on a pixel like 255 - (10,20,30) , I must code like this: 如果我希望在像255(10,20,30)之类的像素上做一个子结构,我必须这样编码:

import numpy as np
pixel = tuple( np.array([255,255,255]) - np.array(pixel) )

is there a faster and easier solution? 有更快更容易的解决方案吗?
Another qustion : is there a way to make a substraction on all pixels, like using a matrix substraction in Matlab: 255 - img (don't use OpenCV build-in function). 另一个问题是:有没有办法对所有像素进行减法,比如在Matlab中使用矩阵减法: 255 - img (不要使用OpenCV内置函数)。

You could use cv2array()/array2cv() functions from adaptors.py in the opencv source distribution and perform all your computation using numpy arrays. 您可以在opencv源代码分发中使用cv2array()/array2cv()函数,并使用numpy数组执行所有计算。 255 - imgarr works in this case. 255 - imgarr适用于这种情况。 Example (stripped-down version of cv2array() for read-only arrays): 示例(用于只读数组的cv2array()的精简版本):

assert isinstance(img, cv.iplimage) and img.depth == cv.IPL_DEPTH_8U
a = np.frombuffer(img.tostring(), dtype=np.uint8)
a.shape = img.height, img.width, img.nChannels
print 255 - a

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM