python画切片图,使用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.

解决方案

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 :

P7Htf.png

Using OpenCV :

7876539b238713e07eb3520d2dca0a48.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值