python 图片匹配 轮廓 截取_如何从图像中剪切轮廓并将其保存到新fi

本文介绍了一种使用Python进行图片处理的方法,包括对图像进行中值模糊、阈值处理和形态学操作来提取轮廓。通过投影到轴上并设定阈值,找到边界并裁剪出目标区域。最终将裁剪的轮廓保存到新的文件中。
摘要由CSDN通过智能技术生成

我在这方面做了一些工作,并裁剪了如下区域。我想这是你想要的。在

Ofdd0.png

cydaV.jpg

基本上,我对图像做这些操作。在

1。median模糊图像、阈值并执行morph-op

2.投影到轴上,阈值并得到边界。在

3.裁剪该区域。在#!/usr/bin/python3

# 2017.10.04 23:45:01 CST

# 2017.10.05 00:52:26 CST

#how to cut a contour from an image and save it to a new file

from matplotlib import pyplot as plt

import numpy as np

import cv2

import time

imgname = "pcb.jpg"

img = cv2.imread(imgname)

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

## medianBlur, threshold and morph-close-op

median = cv2.medianBlur(gray, ksize=17)

retval, threshed = cv2.threshold(median, 110, 255, cv2.THRESH_BINARY_INV)

closed = cv2.morphologyEx(threshed, cv2.MORPH_CLOSE, np.ones(15,15))

## Project to the axis

H,W = img.shape[:2]

xx = np.sum(closed, axis=0)/H

yy = np.sum(closed, axis=1)/W

## Threshold and find the nozero

xx[xx<60] = 0

yy[yy<100] = 0

ixx = xx.nonzero()

iyy = yy.nonzero()

x1,x2 = ixx[0][0], ixx[0][-1]

y1,y2 = iyy[0][0], iyy[0][-1]

## label on the original image and save it.

res1 = cv2.rectangle(img.copy(), (x1,y1),(x2,y2), (0,0,255),2)

res2 = img[y1:y2,x1:x2]

cv2.imwrite("result1.png", res1)

cv2.imwrite("result2.png", res2)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值