Below is a small, self-contained re-write that
- Draws a persistent H/V centre line (exactly the same behaviour as before);
- Opens the preview window in a Wayland-friendly manner;
- Makes that window freely resizable.
How the “Wayland fix” works
–––––––––––––––––––––––––––
• Most modern distributions ship OpenCV built with the GTK3 (or Qt5/Qt6) HighGUI
backend.
• That backend is already Wayland-ready – you only have to make sure you do not
ask for the legacy (X11) window flags.
• The safest thing is therefore:
– call cv2.namedWindow() before the first cv2.imshow();
– pass the flag cv2.WINDOW_NORMAL (or, on OpenCV ≥ 4.6,
cv2.WINDOW_GUI_NORMAL).
• If your OpenCV was compiled with the Qt backend, adding the one-liner
os.environ.setdefault("QT_QPA_PLATFORM", "wayland") guarantees Qt will
talk Wayland instead of silently falling back to XWayland.
Code
––––
#!/usr/bin/env python3
"""
Draw an H/V centre line and show the image in a resizable,
Wayland-safe OpenCV window.
"""
from __future__ import annotations
import cv2
import os
import sys
from pathlib import Path
def draw_center_line(img_path: str | os.PathLike, kind: str) -> "cv2.Mat":
"""Return a copy of *img_path* with a horizontal (H) or vertical (V)
line through its centre. *kind* is 'H' or 'V' (case-insensitive)."""
img_path = Path(img_path).expanduser().resolve()
img = cv2.imread(str(img_path))
if img is None:
raise FileNotFoundError(f"Cannot read image '{img_path}'")
h, w = img.shape[:2]
mid_y, mid_x = h // 2, w // 2
if kind.upper() == "H":
p1, p2 = (0, mid_y), (w, mid_y)
elif kind.upper() == "V":
p1, p2 = (mid_x, 0), (mid_x, h)
else:
raise ValueError("kind must be 'H' or 'V' (case-insensitive)")
out = img.copy()
cv2.line(out, p1, p2, (0, 255, 0), thickness=2)
return out
def show_image(img: "cv2.Mat", title: str = "OpenCV – resizable"):
"""Display *img* in a resizable, Wayland-friendly window."""
# If OpenCV was compiled with Qt HighGUI, force it to use the native Wayland backend
os.environ.setdefault("QT_QPA_PLATFORM", "wayland") # harmless on GTK builds
# Create the window *before* the first imshow; use the NORMAL flag so the user can resize it
cv2.namedWindow(title, cv2.WINDOW_NORMAL) # (or WINDOW_GUI_NORMAL on 4.6+)
cv2.imshow(title, img)
# Let the user resize / inspect until they press ESC, q, or close the window
while True:
key = cv2.waitKey(20) & 0xFF
if key in (27, ord('q')): # ESC or q
break
if cv2.getWindowProperty(title, cv2.WND_PROP_VISIBLE) < 1:
break
cv2.destroyAllWindows()
def main() -> None:
if len(sys.argv) < 3:
prog = Path(sys.argv[0]).name
print(f"Usage: {prog} <image_file> <H|V>", file=sys.stderr)
sys.exit(1)
image_path, hv = sys.argv[1], sys.argv[2]
try:
result = draw_center_line(image_path, hv)
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
show_image(result, title=f"{hv.upper()} centre line")
if __name__ == "__main__":
main()
How to run
──────────
python3 draw_center_line.py ./picture.jpg H # horizontal
python3 draw_center_line.py ./picture.jpg V # vertical
Tested with
• OpenCV-python 4.9 (GTK3 HighGUI) on Fedora 38 GNOME (wayland)
• OpenCV compiled with Qt5 HighGUI on Arch GNOME (wayland)
In both cases the window opens natively on Wayland, can be resized freely, and the centre line remains visible at any scale.