简体   繁体   English

AttributeError: 模块“cv2”没有属性“selectROI”

[英]AttributeError: module 'cv2' has no attribute 'selectROI'

I've got a fresh install of OpenCV 3.2 with contribs, ffmpeg, and numpy.我已经全新安装了带有 contribs、ffmpeg 和 numpy 的 OpenCV 3.2。 However, when I try to use the function selectROI I get an attribute error and I cannot figure out why!!!但是,当我尝试使用函数 selectROI 时,出现属性错误,我不知道为什么!!!

I've tried to reinstall opencv and opencv-contrib however it doesn't seem to change anything.我尝试重新安装 opencv 和 opencv-contrib 但它似乎没有改变任何东西。

import numpy as np
import ffmpy
import cv2
import os

def main():
   ...
            r=0
            cap = cv2.VideoCapture(filename)
           ...
            while cap.grab():
               ...
                if (frame_count>=next_valid):
                    # Initialisation of supporting variables
                    flag, frame = cap.retrieve()
                    if (go_around==0):
                        # Select ROI
                        r = cv2.selectROI(frame)
                    # Cropping and Brightening
                    imCrop = im[int(r[1]):int(r[1]+r[3]), int(r[0]):int(r[0]+r[2])]
                   ...
main()

I just wish I could make a selectable ROI and store the dimensions!我只是希望我可以制作一个可选择的投资回报率并存储尺寸!

在此处输入图片说明

You could always make your own custom ROI selector您始终可以制作自己的自定义 ROI 选择器

import cv2

class ExtractImageWidget(object):
    def __init__(self):
        self.original_image = cv2.imread('1.jpg')

        # Resize image, remove if you want raw image size
        self.original_image = cv2.resize(self.original_image, (640, 556))
        self.clone = self.original_image.copy()

        cv2.namedWindow('image')
        cv2.setMouseCallback('image', self.extract_coordinates)

        # Bounding box reference points and boolean if we are extracting coordinates
        self.image_coordinates = []
        self.extract = False

    def extract_coordinates(self, event, x, y, flags, parameters):
        # Record starting (x,y) coordinates on left mouse button click
        if event == cv2.EVENT_LBUTTONDOWN:
            self.image_coordinates = [(x,y)]
            self.extract = True

        # Record ending (x,y) coordintes on left mouse bottom release
        elif event == cv2.EVENT_LBUTTONUP:
            self.image_coordinates.append((x,y))
            self.extract = False
            print('top left: {}, bottom right: {}'.format(self.image_coordinates[0], self.image_coordinates[1]))

            # Draw rectangle around ROI
            cv2.rectangle(self.clone, self.image_coordinates[0], self.image_coordinates[1], (0,255,0), 2)
            cv2.imshow("image", self.clone) 

        # Clear drawing boxes on right mouse button click
        elif event == cv2.EVENT_RBUTTONDOWN:
            self.clone = self.original_image.copy()

    def show_image(self):
        return self.clone

if __name__ == '__main__':
    extract_image_widget = ExtractImageWidget()
    while True:
        cv2.imshow('image', extract_image_widget.show_image())
        key = cv2.waitKey(1)

        # Close program with keyboard 'q'
        if key == ord('q'):
            cv2.destroyAllWindows()
            exit(1)

An adaptation of nathancy's response that worked better for me,对nathancy的回应的改编对我来说效果更好,

class SelectROI(object):
    def __init__(self, name, im):
        self.image = im
        self.winname = name

        cv2.namedWindow(name)
        self.coords = []
        self.dragging = False
        self._update()

    def _mouse_cb(self, event, x, y, flags, parameters):
        # Record starting (x,y) coordinates on left mouse button click
        if event == cv2.EVENT_LBUTTONDOWN:
            self.coords[:] = [(x, y)]
            self.dragging = True

        elif event == 0 and self.dragging:
            self.coords[1:] = [(x, y)]

        # Record ending (x,y) coordintes on left mouse bottom release
        elif event == cv2.EVENT_LBUTTONUP:
            self.coords[1:] = [(x, y)]
            self.dragging = False
            xs, ys = list(zip(*self.coords))
            self.coords = [(min(xs), min(ys)),
                           (max(xs), max(ys))]
            print('roi:', self.coords)

        # Clear drawing boxes on right mouse button click
        elif event == cv2.EVENT_RBUTTONDOWN:
            self.coords = []
            self.dragging = False

        self._update()

    def _update(self):
        im = self.image.copy()
        if len(self.coords) == 2:
            cv2.rectangle(im, self.coords[0], self.coords[1], (0, 255, 0), 2)
        cv2.imshow(self.winname, im)

    def __call__(self):
        cv2.setMouseCallback(self.winname, self._mouse_cb)
        cv2.waitKey()
        cv2.destroyWindow(self.winname)
        return self.coords if self.coords else None

def select_roi(name, im):
    s=SelectROI(name, im)
    return s()

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

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