2017-01-25 9 views
0

I schwarzes Bild erstellt habe, als ich ein rotes Rechteck in dieses Bild zog. Danach abgeschnitten ich dieses Bild und zog einen ein weiteres Rechteck in die geerntete Bild mit dem Befehl. cv2.rectangle(crop,(50,50),(150,150),(0,0,255),3)OpenCV Python Bild beschneiden

Warum funktioniert das zweite Rechteck in dem Originalbild erscheint, wenn ich es am Ende zeigen? Ich erwartete, nur das erste Rechteck zu sehen.

import cv2 
import numpy as np 

#create image 
image = np.zeros((400,400,3), np.uint8) 

#draw rectangle into original image 
cv2.rectangle(image,(100,100),(300,300),(0,0,255),3) 

#crop image 
crop = image[100:300,100:300] 

#draw rectangle into cropped image 
cv2.rectangle(crop,(50,50),(150,150),(0,0,255),3) 
cv2.imshow('Result', image) 
cv2.waitKey()  

cv2.destroyAllWindows() 

Antwort

2

crop = image[100:300,100:300] schafft eine Ansicht auf dem Originalbild anstelle eines neuen Objekts. Durch Ändern dieser Ansicht wird das zugrunde liegende Originalbild geändert. Weitere Informationen finden Sie unter http://scipy-cookbook.readthedocs.io/items/ViewsVsCopies.html.

Sie können dieses Problem beheben, indem Sie beim Beschneiden eine Kopie erstellen: crop = image[100:300,100:300].copy().

Hinweis: image[100:300,100:300] Parameter sind y: y+h, x: x+w not x: x+w, y: y+h

0

Sie leicht das Bild in Python unter Verwendung

zuschneiden können
roi = oriImage[refPoint[0][1]:refPoint[1][1], refPoint[0][0]:refPoint[1][0]] 

Um die beiden Punkte bekommen Sie cv2.setMouseCallback("image", mouse_crop) aufrufen können. Die Funktion ist so etwas wie dieses

def mouse_crop(event, x, y, flags, param): 
    # grab references to the global variables 
    global x_start, y_start, x_end, y_end, cropping 

    # if the left mouse button was DOWN, start RECORDING 
    # (x, y) coordinates and indicate that cropping is being 
    if event == cv2.EVENT_LBUTTONDOWN: 
     x_start, y_start, x_end, y_end = x, y, x, y 
     cropping = True 

    # Mouse is Moving 
    elif event == cv2.EVENT_MOUSEMOVE: 
     if cropping == True: 
      x_end, y_end = x, y 

    # if the left mouse button was released 
    elif event == cv2.EVENT_LBUTTONUP: 
     # record the ending (x, y) coordinates 
     x_end, y_end = x, y 
     cropping = False # cropping is finished 

     refPoint = [(x_start, y_start), (x_end, y_end)] 

     if len(refPoint) == 2: #when two points were found 
      roi = oriImage[refPoint[0][1]:refPoint[1][1], refPoint[0][0]:refPoint[1][0]] 
      cv2.imshow("Cropped", roi) 

Sie Details von hier können: Mouse Click and Cropping using Python