ARTICLE AD BOX
What you’re running into is Matplotlib’s event loop behavior.
Nothing is “stuck” logically — plt.show() is blocking by default.
Why your code stops at plt.show()
In a normal Python script (not a Jupyter notebook):
plt.show()Blocks execution until all figure windows are closed.
So what actually happens is:
The image window opens
Python waits there
Your remaining OpenCV + Matplotlib code will not run
Only after you close the window does execution continue
This is expected behavior.
Correct mental model
plt.show() = “Start GUI loop and wait until user closes the figure(s)”
This is different from cv2.imshow(), which continues after cv2.waitKey()
Best solutions (pick one)
Solution 1: Call plt.show() only once (recommended)
Matplotlib is designed to show all figures at the end.
plt.figure(figsize=[10, 10]) plt.title("Image") plt.axis("off") plt.imshow(image[:, :, ::-1]) # ---- processing continues ---- plt.figure(figsize=[30, 30]) plt.subplot(131) plt.imshow(image_sharp[:, :, ::-1]) plt.title("Final Image") plt.axis("off") plt.subplot(132) plt.imshow(image_cleared[:, :, ::-1]) plt.title("Clear Impurities") plt.axis("off") plt.subplot(133) plt.imshow(image[:, :, ::-1]) plt.title("Original") plt.axis("off") plt.show() # <-- only here✔ Clean
✔ Idiomatic Matplotlib
✔ No blocking surprises
Solution 2: Non-blocking show
If you must show something mid-script:
plt.show(block=False) plt.pause(0.001) # allow GUI event loop to updateExample:
plt.imshow(image[:, :, ::-1]) plt.axis("off") plt.show(block=False) plt.pause(0.5) # show for half a secondSolution 3: Interactive mode
Enable interactive plotting:
plt.ion()Then plt.show() becomes non-blocking:
plt.ion() plt.imshow(image[:, :, ::-1]) plt.show() # code continues immediatelyTo disable later:
plt.ioff() plt.show()Useful for debugging or step-by-step visualization.
Solution 4: Save instead of display (best for pipelines)
For scripts or batch processing:
plt.imshow(image[:, :, ::-1]) plt.axis("off") plt.savefig("step1.png", bbox_inches="tight") plt.close()No GUI
No blocking
Fully automated
