CV Lab2
CV Lab2
Nasihatkon
Spring 2025
Side note: if we use cv2.waitKey() without waiting time, it will wait for the user to
press a key to continue.
Fundamentals of Computer Vision (Undergrad) - B. Nasihatkon
Spring 2025
● Are the image colors strange? Remember scipy/matplotlib use the RGB
system, while opencv uses the BGR system. Reading an image with opencv
and displaying with matplotlib makes the blue and red channels swapped.
>>> plt.imshow(I[:,:,::-1])
>>> plt.show()
Remember, I[:,:,::-1] reverses the order of the last dimension (the channels)
and hence converts BGR (opencv) to RGB (for displaying with matplotlib).
Could you suggest another way using cv2 for the above conversion?
>>> I[:,:,1] = 0
>>> plt.imshow(I[:,:,::-1])
>>> plt.show()
Saving an image
>>> cv2.imwrite('lake_nogreen.jpg', I)
I = cv2.imread('lake.jpg')
Fundamentals of Computer Vision (Undergrad) - B. Nasihatkon
Spring 2025
cv2.imshow('win1',I)
while 1:
k = cv2.waitKey()
if k == ord('o'):
cv2.imshow('win1',I)
elif k == ord('b'):
cv2.imshow('win1',B)
elif k == ord('g'):
cv2.imshow('win1',G)
elif k == ord('r'):
cv2.imshow('win1',R)
elif k == ord('q'):
cv2.destroyAllWindows()
break
Task 1:
The above code shows the B, G and R channels as grayscale images. Change the
above code so that the blue channel is displayed in the blue, green channel in the
green, and red channel in red. Notice that since these are color images they have to
be mxnx3 arrays. For a purely red image, the green and blue channels are entirely
zero. The following code might help:
B = np.zeros(I.shape, dtype=np.uint8)
print(B.shape)
B[:,:,0] = I[:,:,0]
Method 1:
import cv2
import numpy as np
I = cv2.imread('damavand.jpg')
J = cv2.imread('eram.jpg')
print(I.shape)
print(J.shape)
K = I.copy()
K[::2,::2,:] = J[::2,::2,:]
cv2.imshow("Image 1", I)
cv2.imshow("Image 2", J)
cv2.imshow("Blending", K)
cv2.waitKey(3000)
cv2.destroyAllWindows()
Method 2
K = I//2+J//2
>>> a+b
>>> cv2.add(a,b)
● What is the difference between a+b and cv2.add(a,b)? Which one do you
think should be used for adding up images?
K = cv2.addWeighted(I,0.8,J,0.2, 0)
K = cv2.addWeighted(I,0.1,J,0.9, 0)
K = cv2.addWeighted(I,0.3,J,0.7, 0)
Task 2:
Make an animated smooth transition from the image I to the J. You can use
“cv2.waitKey(n)” to delay for n milliseconds.
Task 3:
Create a smooth animation that changes image I from grayscale to color.
Hint: Grayscale images have equal values in all three color channels.
Fundamentals of Computer Vision (Undergrad) - B. Nasihatkon
Spring 2025
References
● https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_core/py_table_of_conten
ts_core/py_table_of_contents_core.html#py-table-of-content-core
● https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_
image_display/py_image_display.html