#主要内容
- Access pixel values and modify them
- Access image properties
- Setting Region of Image (ROI)
- Splitting and Merging images
#获取和修改各像素值
##Accessing and Modifying pixel values
You can access a pixel value by its row and column coordinates. For BGR image, it returns an array of Blue, Green, Red values. For grayscale image, just corresponding intensity is returned.
|
|
警告 Numpy is a optimized library for fast array calculations. So simply accessing each and every pixel values and modifying it will be very slow and it is discouraged.
##更快的方法
Above mentioned method is normally used for selecting a region of array, say first 5 rows and last 3 columns like that. For individual pixel access, Numpy array methods, array.item() and array.itemset() is considered to be better. But it always returns a scalar. So if you want to access all B,G,R values, you need to call array.item() separately for all.
|
|
##OpenCV的坐标问题
原点在左上角
向右为X正方向,向下为Y正方向
另外要注意,在numpy设定图片大小时x,y是互换的。
比如img.shape是(600,800,3)
那么X方向有800像素,Y方向有600像素
即是在numpy的ndarray中
坐标方式是 [Y,X,CHANNEL]
#获取图像属性
##Accessing Image Properties
Image properties include number of rows
, columns
and channels
, type of image data
, number of pixels
etc.
Shape of image is accessed by img.shape. It returns a tuple of number of rows, columns and channels (if image is color):
|
|
number of pixels is accessed by img.size
|
|
size的计算方法
size = rows columns channels
Image datatype is obtained by img.dtype
:
|
|
#ROI操作
##image ROI
ROI(region of interest)
ROI is again obtained using Numpy indexing.
|
|
#分割与合并图像通道
##Splitting and Merging Image Channels
警告
cv2.split()
is a costly operation (in terms of time), so only use it if necessary. Numpy indexing is much more efficient and should be used if possible.
#为图像添加边缘
##Making Borders for Images (Padding)
填充边缘的一些方式
If you want to create a border around the image, something like a photo frame, you can use cv2.copyMakeBorder() function. But it has more applications for convolution operation, zero padding etc. This function takes following arguments:
This function takes following arguments:
src
- input imagetop
,bottom
,left
,right
- border width in number of pixels in corresponding directionsborderType
- Flag defining what kind of border to be added. It can be following types:
- cv2.BORDER_CONSTANT - Adds a constant colored border. The value should be given as next argument.
- cv2.BORDER_REFLECT - Border will be mirror reflection of the border elements, like this : fedcba|abcdefgh|hgfedcb
- cv2.BORDER_REFLECT_101 or cv2.BORDER_DEFAULT - Same as above, but with a slight change, like this : gfedcb|abcdefgh|gfedcba
- cv2.BORDER_REPLICATE - Last element is replicated throughout, like this: aaaaaa|abcdefgh|hhhhhhh
- cv2.BORDER_WRAP - Can’t explain, it will look like this : cdefgh|abcdefgh|abcdefg
value
- Color of border if border type is cv2.BORDER_CONSTANT
demo code
结果
关于什么是zero-padding
#参考资料
[1] OpenCV-Python Tutorial:Basic Operations on Images
[2] zero-padding 边缘填充