如何使用Python在OpenCV中裁剪图像 [英] How to crop an image in OpenCV using Python

查看:563
本文介绍了如何使用Python在OpenCV中裁剪图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何像以前在PIL中一样使用OpenCV裁剪图像.

How can I crop images, like I've done before in PIL, using OpenCV.

PIL上的工作示例

im = Image.open('0.png').convert('L')
im = im.crop((1, 1, 98, 33))
im.save('_0.png')

但是我如何在OpenCV上做到这一点?

But how I can do it on OpenCV?

这是我尝试过的:

im = cv.imread('0.png', cv.CV_LOAD_IMAGE_GRAYSCALE)
(thresh, im_bw) = cv.threshold(im, 128, 255, cv.THRESH_OTSU)
im = cv.getRectSubPix(im_bw, (98, 33), (1, 1))
cv.imshow('Img', im)
cv.waitKey(0)

但这是行不通的.

我认为我错误地使用了getRectSubPix.如果是这种情况,请说明如何正确使用此功能.

I think I incorrectly used getRectSubPix. If this is the case, please explain how I can correctly use this function.

推荐答案

这很简单.使用numpy切片.

It's very simple. Use numpy slicing.

import cv2
img = cv2.imread("lenna.png")
crop_img = img[y:y+h, x:x+w]
cv2.imshow("cropped", crop_img)
cv2.waitKey(0)

这篇关于如何使用Python在OpenCV中裁剪图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆