java和python+opencv实现图像框图

351 阅读1分钟

public static String drawRect(String imageUrl, List<Region> regionList) {
        try {
            BufferedImage image = ImageIO.read(new File(imageUrl));
            Graphics2D g = (Graphics2D) image.getGraphics();
            g.setStroke(new BasicStroke(3.0f));
            for (Region region: regionList) {
                if (region.getResult()) {
                    g.setColor(Color.RED);//画笔颜色
                } else {
                    g.setColor(Color.BLUE);
                }
                g.drawRect(region.getX(), region.getY(), region.getW(), region.getH());
            }

            FileOutputStream out = new FileOutputStream(imageUrl.replace(".jpg", "-1.jpg"));//输出图片的地址

            ImageIO.write(image, "jpeg", out);
        } catch (MalformedURLException e1) {
            System.out.println(e1);
        } catch (IOException e2) {
            System.out.println(e2);
        }
        return "";
    }



public class Region {
    private int x;
    private int y;
    private int w;
    private int h;
    private boolean result;

}


拿到原始图片,循环需要框图的坐标列表,做原始图片的多个标注框图,也可以在框图区域显示文字

import cv2fname = r'D:\real.jpg'
img = cv2.imread(fname)# 画矩形框# 
输入参数分别为图像、左上角坐标、右下角坐标、颜色数组、粗细
Left = 789
left2 = 800
Top = 429
top = 450
Height = 85
height = 100
Width = 77
width = 90
pt1 = (Left, Top)  
# 左上坐标
pt2 = (Left + Width, Top + Height)  
# 右下坐标'''框多个区域'''
# pt3 = (left2,top)
# pt4 = (left2+width,top+height)
cv2.rectangle(img, pt1, pt2, (255, 0, 0), 2)
# cv2.rectangle(img, pt3, pt4, (255, 0, 0), 2)  # 框图多个区域
cv2.imwrite('new.jpg', img)