简体   繁体   中英

AttributeError: module 'cv2' has no attribute 'selectROI'

I've got a fresh install of OpenCV 3.2 with contribs, ffmpeg, and numpy. However, when I try to use the function selectROI I get an attribute error and I cannot figure out why!!!

I've tried to reinstall opencv and opencv-contrib however it doesn't seem to change anything.

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

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,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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