在OpenCV中,cv2.imshow显示的图片太大了,缩放方法_cv2.imshow 缩放
方法1:缩放图片后再显示
直接调整图片尺寸(推荐,兼容性更好):
import cv2# 读取原始图片img = cv2.imread(\"large_image.jpg\")# 定义缩放比例(例如缩放到原图的50%)scale_percent = 50 # 百分比width = int(img.shape[1] * scale_percent / 100)height = int(img.shape[0] * scale_percent / 100)dim = (width, height)resized = cv2.resize(img, dim, interpolation=cv2.INTER_AREA)# 或直接指定目标尺寸(例如800x600)# resized = cv2.resize(img, (800, 600), interpolation=cv2.INTER_AREA)cv2.imshow(\"Resized Image\", resized)cv2.waitKey(0)cv2.destroyAllWindows()
保持宽高比的缩放
def resize_with_aspect_ratio(img, width=None, height=None): \"\"\" 按比例缩放图片(指定宽度或高度) \"\"\" h, w = img.shape[:2] if width is None and height is None: return img if width is not None: ratio = width / w dim = (width, int(h * ratio)) else: ratio = height / h dim = (int(w * ratio), height) return cv2.resize(img, dim, interpolation=cv2.INTER_AREA)# 示例:固定宽度为800pxresized_img = resize_with_aspect_ratio(img, width=800)cv2.imshow(\"Fixed Width\", resized_img)
方法2:允许窗口自由缩放
设置窗口属性为可调整模式:
# 创建可调整大小的窗口cv2.namedWindow(\"Resizable Window\", cv2.WINDOW_NORMAL)cv2.imshow(\"Resizable Window\", img)cv2.waitKey(0)
关键参数说明
cv2.resize()
interpolation
cv2.INTER_AREA
(缩小推荐)或cv2.INTER_CUBIC
(放大推荐)cv2.WINDOW_NORMAL
效果对比
完整示例代码
import cv2img = cv2.imread(\"large_image.jpg\")# 方法1:缩放到指定宽度(保持比例)resized = resize_with_aspect_ratio(img, width=800)# 方法2:创建可调整窗口cv2.namedWindow(\"Adjustable Window\", cv2.WINDOW_NORMAL)cv2.imshow(\"Adjustable Window\", img)cv2.waitKey(0)cv2.destroyAllWindows()
选择方案时:
-
若需精确控制显示尺寸,使用方法1
-
若需快速查看原图细节,使用方法2(拖动窗口+鼠标滚轮缩放)