Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV python: cv2.split() vs slicing while getting channel in BGR-image

I want to get only the first channel (Blue) in BGR-image and then save it to disk. When I use cv2.split() everything is ok

>>> import cv2
>>> a = cv2.imread("/home/s18/theVIDEO/1_resized.jpg")
>>> b = cv2.split(a)[0]
>>> type(b)
<type 'numpy.ndarray'>                                                                                              
>>> b                                                                                              
array([[223, 222, 224, ...,  88,  80,  71],
[222, 221, 225, ...,  84,  78,  67],
[220, 221, 225, ...,  77,  71,  62],
..., 
[163, 178, 182, ..., 107, 107, 106],
[148, 170, 186, ..., 104, 104, 103],
[156, 181, 201, ..., 102, 101, 100]], dtype=uint8)
>>> b.shape
(600, 800)
>>> cv2.imwrite("/home/s18/theVIDEO/1_resized2.jpg", b)
True

But while using simular slicing operation I get error

>>> c = a[:,:,0]
>>> c
>>> type(c)
<type 'numpy.ndarray'>                                                                                              
array([[223, 222, 224, ...,  88,  80,  71],
[222, 221, 225, ...,  84,  78,  67],
[220, 221, 225, ...,  77,  71,  62],
..., 
[163, 178, 182, ..., 107, 107, 106],
[148, 170, 186, ..., 104, 104, 103],
[156, 181, 201, ..., 102, 101, 100]], dtype=uint8)
>>> c.shape
(600, 800)
>>> cv2.imwrite("/home/s18/theVIDEO/1_resized3.jpg", c)
False

Elements in arrays b and c are equal, dimensions and classes are also simular. Why couldn't I use simple slicing to get one of the channels?

like image 616
s18 Avatar asked Nov 04 '22 10:11

s18


1 Answers

It turns out OK if you didn't slice directly but copying the contents instead

...
>>> c = zeros((a.shape[0],a.shape[1]), dtype=a.dtype)
>>> c[:,:] = a[:,:,0]
>>> cv2.imwrite('out.jpg', c)
True
like image 178
Peb Avatar answered Nov 09 '22 14:11

Peb