【问题标题】:python to crop and save irregular image or crop and place it in the centre without resizingpython裁剪并保存不规则图像或裁剪并将其放置在中心而不调整大小
【发布时间】:2019-07-09 06:17:54
【问题描述】:

我正在为需要制作模板的图像比较工作。

当前图片:

我可以为所需的图像上色,但无法裁剪所需的图像,颜色图像的代码如下:

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

输出:

  1. 我想裁剪 红色 的图像。
  2. 使用不规则尺寸保存裁剪图像。
  3. 除了 cv2.drawContours
  4. 还有其他方法可以获取所需的图像吗

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

使用 python 帮助我解决问题。

【问题讨论】:

  • 保存不规则尺寸的裁剪图像 ?我认为这是不可能的,因为图像通常被认为是mxn 矩阵但是您可以使用 alpha 通道来隐藏图像的某些部分,但它总是会是完美的矩形。
  • @ZdaR 我会试试 alpha 通道
  • 看看this post

标签: python opencv image-processing crop image-compression


【解决方案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);

现在你可以使用这个矩形从原始图像中获取一个子垫

cv::Mat roi = img(rect);

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

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

【讨论】:

  • 代码几乎一样,按照我说的步骤就可以了。
  • 我被困在创建蒙版中,因为mask = mask(roi); 没有蒙版功能,还想知道蒙版是什么意思??
  • 掩码不是函数,掩码在这里声明cv::Mat mask。蒙版用于复制您在那里检测到颜色的图像部分。所以 mask 告诉 copyTo 函数只复制这些像素。否则,将复制整个图像。
  • 唯一剩下的就是我无法制作不规则的边框,因为我正在使用cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)' in python which is use to make rectangle over the object. any alternative for cv2.rectangle(img,(x,y),(x+w,y+h),(0,255 ,0),2)` 这将使我能够在对象上制作不规则的边框。
  • 完全没有不规则的边框图片。
猜你喜欢
  • 2011-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-16
  • 1970-01-01
  • 2011-11-11
  • 2015-11-09
  • 1970-01-01
相关资源
最近更新 更多