繁体   English   中英

如何在Python中使用OpenCV翻译图像的一小部分

[英]How to translate a small section of an image using OpenCV in Python

我具有下半圆的左上角的坐标,并且知道半圆的长度和宽度(如果将其围成矩形)。 我想做的是将底部半圆向上平移4个像素。 因此,有人可以提供一些代码来翻译图像的一部分,从而知道所有坐标吗? 谢谢。

图片

感谢@Rachel L的帮助,但我不久前就知道了。 基本上,我创建了一个单独的图像,该图像在底部包含半圆,然后使用一种方法在底部获得每个半圆的左上角。 然后,我弄清楚了半圆的长度和宽度,并移动了盒子中的所有黑色像素,创建了5个对齐它的单位。

我可能应该补充说,这是一个更大的项目的一部分,在该项目中,我需要从图像中移出底部的所有半圆,以便它们都对齐,这意味着我不知道它们的坐标。 图片

半圆位置提取方法

def extract(name1, name2):
img_rgb = cv2.imread(name1)
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template = cv2.imread(name2,0)   
res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where( res >= threshold)
arr = []
for pt in zip(*loc[::-1]):
    if "down" in name2:
        pt = (pt[0], pt[1] + 1)
    arr.append(pt)
return arr

代码向上移动半圆

locFillSemiDown = extract('img' + str(num) + '.png', 'filledsemidown.png')

for loc in locSemiDown:
   for y in range(loc[0], loc[0] + 11):
      for x in range(loc[1], loc[1] + 6):
         if(img.item(x,y,0) == 0 and img.item(x,y,1) == 0 and img.item(x,y,2) == 0):  
            img.itemset((x - 5, y,0),0)
            img.itemset((x - 5, y,1),0)
            img.itemset((x - 5, y,2),0)
            img.itemset((x, y,0),0)
            img.itemset((x, y,1),255)
            img.itemset((x, y,2),255)

在此处输入图片说明

对于该特定图像,您可以抓住矩形再加上4-6像素的行,然后将该ROI放到想要的像素高4像素的图像上。

这是用C ++编写的,但是应该足够类似,您可以对其进行翻译。

#include "stdafx.h"
#include <opencv/cxcore.h>
#include <opencv2\core\mat.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <opencv/cxcore.h>
#include <opencv/cv.h>
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>

using namespace cv;
using namespace std;


int main() {

    //getting the image
    Mat image = imread("C:/this/is/a/link/to/an/image.png");

    //create new image that looks exactly like old image
    Mat new_image = image.clone();

    //showing the image
    namedWindow("Image", CV_WINDOW_NORMAL| CV_WINDOW_KEEPRATIO | CV_GUI_EXPANDED); 
    imshow("Image", image);
    waitKey(0);

    //getting the roi coordinates
    int x = 13, y = 8; //eyeballing the coordinates
    int w = 26-x, h = 20-y; //more eyeballing the coordinates

    //grabbing the roi
    Rect roi = Rect(x, y, w, h);
    Mat img_roi = image(roi);

    //creating the new roi
    Rect new_roi = Rect(x, y-4, w, h);

    //copying the old roi onto the  new image in the space of the new roi
    img_roi.copyTo(new_image(new_roi));

    //displaying the image
    imshow("Image", new_image);
    waitKey(0);

    //saving the new image
    imwrite("C:/this/is/a/link/to/a/newimage.png", new_image);

}

结果:

固定档图片

现在,此方法可行,因为您可以在要查找的矩形下方抓取更多黄色,从而可以将其抓取。

如果将其精确地修剪为要移动的矩形,那么它将仅将roi覆盖在旧图像上,最终将得到“已移动”图像的一部分。

像这样:

矩形较短的固定文件的图像

暂无
暂无

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

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