python裁剪并保存不规则图像或裁剪并将其放在中心而不调整大小

问题描述 投票:1回答:1

我正在进行图像比较,我需要制作一个模板。

当前图片:

original image

我能够为所需的图像着色但不能裁剪所需的图像,彩色图像的代码如下:

import numpy as np
import cv2

img = cv2.imread('./org.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret,thresh = cv2.threshold(gray,127,255,1)

contours,h = cv2.findContours(thresh,1,2)

for cnt in contours:
    approx = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
    print (len(approx))
    if len(approx)==5:
        # print "pentagon"
        cv2.drawContours(img,[cnt],0,255,-1)
    elif len(approx)==3:
        # print "triangle"
        cv2.drawContours(img,[cnt],0,(0,255,0),-1)
    elif len(approx)==4:
        # print "square"
        cv2.drawContours(img,[cnt],0,(0,0,255),-1)
    elif len(approx) == 9:
        # print "half-circle"
        cv2.drawContours(img,[cnt],0,(255,255,0),-1)
    elif len(approx) > 15:
        # print "circle"
        cv2.drawContours(img,[cnt],0,(0,255,255),-1)

cv2.imwrite('./test/Image_crop.jpg', img)
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

输出:

output image

  1. 我想要裁剪出红色的图像。
  2. 使用不规则尺寸保存裁剪图像。
  3. 有没有其他方法来获得所需的图像而不是cv2.drawContours

问题取决于:Python libraries failed for detailed image comparison between two shifted images captured using webcam

帮我解决使用python的问题。

python opencv image-processing crop image-compression
1个回答
1
投票

您可以从轮廓创建mask并使用此蒙版从原始图像进行复制,然后您可以保存图像。

cv::Mat dst;
originalIamge.copyTo(dst, mask);
cv::imwite("path/where/to/save.jpg", dst);

更新:更多细节。

从计数器cv::boundingRect(contour)创建一个边界框

cv::Rect rect = cv::boundingRect(contour);

现在你可以使用这个rec​​t从原始Image中获取一个submat

cv::Mat roi = img(rect);

然后创建一个与Mat大小相同的新ROI

cv::Mat dst = cv::Mat::create(roi.size(), CV_8UC3);

并创建一个面具

cv::Mat mask = cv::Mat::zeros(img.size(), CV_8UC1);
cv::drawContours(mask, contours, 0, cv::Scalar(255), cv::FILLED);
mask = mask(roi);

现在,您可以使用蒙版复制图像的所需部分

roi .copyTo(dst, mask);

并保存

cv::imwite("path/where/to/save.jpg", dst);
© www.soinside.com 2019 - 2024. All rights reserved.