Opencv Python Cropping Image
I've created black image, than I drew a red rectangle into this image. Afterwards I cropped this image and drew a another rectangle into the cropped image using the command. cv2.r
Solution 1:
crop = image[100:300,100:300]
creates a view on the original image instead of a new object. Modifying that view will modify the underlying original image. See http://scipy-cookbook.readthedocs.io/items/ViewsVsCopies.html for more details.
You can resolve this issue by creating a copy when cropping:
crop = image[100:300,100:300].copy()
.
Note: image[100:300,100:300]
parameters are y: y+h, x: x+w
not x: x+w, y: y+h
Solution 2:
if you want to save the cropped image, just add this code:
cv2.imwrite("Cropped.jpg", roi)
after cv2.imshow("Cropped", roi)
I hope this helps.
Solution 3:
you can easily crop the image in python by using
roi = oriImage[refPoint[0][1]:refPoint[1][1], refPoint[0][0]:refPoint[1][0]]
In order to get the two points you can call cv2.setMouseCallback("image", mouse_crop)
.
The function is something like this
defmouse_crop(event, x, y, flags, param):
# grab references to the global variablesglobal 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 beingif event == cv2.EVENT_LBUTTONDOWN:
x_start, y_start, x_end, y_end = x, y, x, y
cropping = True# Mouse is Movingelif event == cv2.EVENT_MOUSEMOVE:
if cropping == True:
x_end, y_end = x, y
# if the left mouse button was releasedelif 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)]
iflen(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)
You can get details from here : Mouse Click and Cropping using Python
Post a Comment for "Opencv Python Cropping Image"