Python OpenCV: Resize Image and Window Simultaneously
This code demonstrates how to resize both an image and its display window using OpenCV in Python.
img = cv2.imread('lena.png')
h, w, c = img.shape
cv2.namedWindow('lena')
cv2.imshow('lena', img)
cv2.waitKey(500)
# Resize image
resized_img = cv2.resize(img, (w//2, h//2))
# Display resized image in resized window
cv2.imshow('lena', resized_img)
cv2.waitKey(0)
Explanation:
-
Load Image:
img = cv2.imread('lena.png')loads the image file 'lena.png' using OpenCV'simread()function. -
Get Dimensions:
h, w, c = img.shaperetrieves the height (h), width (w), and number of channels (c) of the image. -
Create Window:
cv2.namedWindow('lena')creates a window named 'lena' to display the image. -
Show Image:
cv2.imshow('lena', img)displays the original image in the window. -
Wait for 500ms:
cv2.waitKey(500)pauses the execution for 500 milliseconds, allowing you to see the original image before resizing. -
Resize Image:
resized_img = cv2.resize(img, (w//2, h//2))resizes the image to half its original dimensions usingcv2.resize(). The(w//2, h//2)tuple specifies the new width and height. -
Display Resized Image:
cv2.imshow('lena', resized_img)displays the resized image in the same window, 'lena'. -
Wait Indefinitely:
cv2.waitKey(0)pauses the execution until a key is pressed, keeping the window open until the user is ready to close it.
原文地址: http://www.cveoy.top/t/topic/fpR7 著作权归作者所有。请勿转载和采集!