使用 Python 和 OpenCV 中的切片从图像中提取区域
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15072736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Extracting a region from an image using slicing in Python, OpenCV
提问by Booyaches
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.
我无法弄清楚如何用颜色来做。我想到了提取每个通道R、G、B;从每个通道切下这个区域并将它们合并在一起,但必须有更短的方法。
采纳答案by Abid Rahman K
There is a slight difference in pixel ordering in OpenCV and Matplotlib.
OpenCV 和 Matplotlib 中的像素排序略有不同。
OpenCV follows BGR order, while matplotlib likely follows RGB order.
OpenCV 遵循 BGR 顺序,而 matplotlib 可能遵循 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:
因此,当您使用 pylab 函数显示在 OpenCV 中加载的图像时,您可能需要将其转换为 RGB 模式。(我不确定是否有任何简单的方法)。下面的方法演示它:
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.
注意:请查看下面@Amro 的评论,以获得更好的 BGR 和 RGB 之间的转换方法。img2 = img[:,:,::-1]. 很简单。
Run this code and see the difference in result yourself. Below is what I got :
运行此代码并自己查看结果的差异。以下是我得到的:
Using Matplotlib :
使用 Matplotlib :


Using OpenCV :
使用 OpenCV :


回答by Israel Unterman
2 more options not mentioned yet:
还没有提到另外 2 个选项:
img[..., ::-1] # same as the mentioned img[:, :, ::-1] but slightly shorter
and the versatile
和多才多艺的
cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
回答by Sravan Chittupalli
Best way to do this is to use :-
img2 = cv2.cvtColor(img , cv2.COLOR_BGR2RGB)
This will convert the BGR 'img' array to RGB 'img2' array. Now you can use img2 array for imshow() function of matplotlib.
最好的方法是使用 :-
img2 = cv2.cvtColor(img , cv2.COLOR_BGR2RGB)
这会将 BGR 'img' 数组转换为 RGB 'img2' 数组。现在您可以将 img2 数组用于 matplotlib 的 imshow() 函数。
Refer Link:- cvtColor
参考链接:- cvtColor

