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:

  1. Load Image: img = cv2.imread('lena.png') loads the image file 'lena.png' using OpenCV's imread() function.

  2. Get Dimensions: h, w, c = img.shape retrieves the height (h), width (w), and number of channels (c) of the image.

  3. Create Window: cv2.namedWindow('lena') creates a window named 'lena' to display the image.

  4. Show Image: cv2.imshow('lena', img) displays the original image in the window.

  5. Wait for 500ms: cv2.waitKey(500) pauses the execution for 500 milliseconds, allowing you to see the original image before resizing.

  6. Resize Image: resized_img = cv2.resize(img, (w//2, h//2)) resizes the image to half its original dimensions using cv2.resize(). The (w//2, h//2) tuple specifies the new width and height.

  7. Display Resized Image: cv2.imshow('lena', resized_img) displays the resized image in the same window, 'lena'.

  8. 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.

Python OpenCV: Resize Image and Window Simultaneously

原文地址: http://www.cveoy.top/t/topic/fpR7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录