繁体   English   中英

使用OpenCV和Python裁剪图像

[英]Crop Contures of Image with OpenCV and Python

我正在尝试找出医学图像重要部分的图像尺寸,如下所示。 我正在使用OpenCV和Python。

在此处输入图片说明

我必须先裁剪图像,以消除图像周围的黑色空间。 这是我的代码:

import cv2
import numpy as np

img = cv2.imread('image-000.png')

height, width, channels = img.shape     #shape of original image

height_2 = height * 7/100
width_2 = width * 15/100

img[0:height_2, 0:width_2] = [0, 0, 0]    #get rid of the watermark on the top left

gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
_,thresh = cv2.threshold(gray,15,255,cv2.THRESH_BINARY)

_, contours, _= cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnt = contours[0]

x,y,w,h = cv2.boundingRect(cnt)

crop = img[y:y+h,x:x+w]

height_2, width_2, channels_2 = crop.shape
print "height: " + repr(height_2)
print "width: " + repr(width_2)


cv2.waitKey(0)
cv2.destroyAllWindows()

这段代码适用于上面的图片:

在此处输入图片说明

但是,当我想对其他图像使用相同的代码时,它将不起作用。 例如,这不起作用:

在此处输入图片说明

你知道我在做什么错吗? 非常感谢您的帮助!

问题是在第二张图像中找到的轮廓多于1个。 只需将cnt = contours[0] cnt = max(contours, key=cv2.contourArea) cnt = contours[0]替换为cnt = max(contours, key=cv2.contourArea) ,它将为您提供最大的轮廓。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM