Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting a region from an image using slicing in Python, OpenCV

I have an image and I want to extract a region from it. I have coordinates of left upper corner and right lower corner of this region. In gray scale I do it like this:

I = cv2.imread("lena.png") I = cv2.cvtColor(I, cv2.COLOR_RGB2GRAY) region = I[248:280,245:288] tools.show_1_image_pylab(region) 

I can't figure it out how to do it in color. I thought of extracting each channel R, G, B; slicing this region from each of the channels and to merge them back together but there is gotta be a shorter way.

like image 725
Booyaches Avatar asked Feb 25 '13 17:02

Booyaches


People also ask

How do you find the region of interest in image processing in Python?

Python OpenCV – selectroi() Function With this method, we can select a range of interest in an image manually by selecting the area on the image. Parameter: window_name: name of the window where selection process will be shown. source image: image to select a ROI.

How do I split an image in OpenCV?

In this article, we will learn how to split a multi-channel image into separate channels and combine those separate channels into a multi-channel image using OpenCV in Python. To do this, we use cv2. split() and cv2. merge() functions respectively.


2 Answers

There is a slight difference in pixel ordering in OpenCV and Matplotlib.

OpenCV follows BGR order, while matplotlib likely follows RGB order.

So when you display an image loaded in OpenCV using pylab functions, you may need to convert it into RGB mode. ( I am not sure if any easy method is there). Below method demonstrate it:

import cv2 import numpy as np import matplotlib.pyplot as plt  img = cv2.imread('messi4.jpg') b,g,r = cv2.split(img) img2 = cv2.merge([r,g,b]) plt.subplot(121);plt.imshow(img) # expects distorted color plt.subplot(122);plt.imshow(img2) # expect true color plt.show()  cv2.imshow('bgr image',img) # expects true color cv2.imshow('rgb image',img2) # expects distorted color cv2.waitKey(0) cv2.destroyAllWindows() 

NB : Please check @Amro 's comment below for better method of conversion between BGR and RGB. img2 = img[:,:,::-1] . Very simple.

Run this code and see the difference in result yourself. Below is what I got :

Using Matplotlib :

enter image description here

Using OpenCV :

enter image description here

like image 125
Abid Rahman K Avatar answered Sep 29 '22 08:09

Abid Rahman K


2 more options not mentioned yet:

img[..., ::-1] # same as the mentioned img[:, :, ::-1] but slightly shorter 

and the versatile

cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 
like image 27
Israel Unterman Avatar answered Sep 29 '22 06:09

Israel Unterman