简体   繁体   English

使用OpenCV和Python裁剪图像

[英]Crop Contures of Image with OpenCV and Python

I'm trying to find out the image size of the important part of a medical image as seen below. 我正在尝试找出医学图像重要部分的图像尺寸,如下所示。 I am using OpenCV and Python. 我正在使用OpenCV和Python。

在此处输入图片说明

I have to crop the image first to get rid of the black space around the image. 我必须先裁剪图像,以消除图像周围的黑色空间。 Here is my Code: 这是我的代码:

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()

This code works fine for the image above: 这段代码适用于上面的图片:

在此处输入图片说明

However when I want to use the same code for other images it doesnt work. 但是,当我想对其他图像使用相同的代码时,它将不起作用。 For example this doesnt work: 例如,这不起作用:

在此处输入图片说明

Do you know what I am doing wrong? 你知道我在做什么错吗? Your help would be highly appreciated! 非常感谢您的帮助!

The problem is that you find more then 1 contour in the second image. 问题是在第二张图像中找到的轮廓多于1个。 Just replace your line cnt = contours[0] with cnt = max(contours, key=cv2.contourArea) and it will just get the biggest contour for you. 只需将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