使用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)
我无法弄明白如何用它做颜色。我想提取每个通道R,G,B;从每个通道切割这个区域并将它们合并在一起但是必须有一个更短的方法。
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.
OpenCV和Matplotlib中的像素排序略有不同。
There is a slight difference in pixel ordering in OpenCV and Matplotlib.
OpenCV遵循BGR顺序,而matplotlib可能遵循RGB顺序。
OpenCV follows BGR order, while matplotlib likely follows RGB order.
因此当您使用pylab函数显示在OpenCV中加载的图像时,您可能需要将其转换为RGB模式。 (我不确定是否有任何简单的方法)。下面的方法演示了它:
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:请检查@Amro的评论如下是BGR和RGB之间更好的转换方法。 img2 = img [:,:, - - 1]
。非常简单。
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 :
使用Matplotlib:
使用OpenCV: