You are on page 1of 14

Student ID

(1)OpenCV
1911562106 TP No./卷号:A
Total
Name Result
PARVEZ 朴维
Reviewer Hubei University of Technology
191c 软工 2021 to 2022 Academic Year Second Semester, Final Exam
二 O 二一 — 二 O 二二 学年第二学期期末考试

Computer Graphics 试题/Test Paper


(For Majors of Computer Science, Software Engineering)Open-book
(计算机科学 软件工程 专业用)开卷

Q
I II III IV V VI VII VIII IX X
No.
Q 20 20 60
Result
Your
Result
Notice: Student ID, TSA and Grade & Class are not filled properly, the paper is invalid.
注意:学号、姓名和所在年级班级不写、不写全或写在密封线外者,试卷作废。

Result I、terms to explain(5’×4)


Reviewer

1
(2)Cathode Ray Tube (3)OpenGL

2
(4)Matplotlib

II、Scripts (5’×4)
Result
Reviewer

(1)Write some codes to show pictue and save it to “star.jpg”

Answer:

import cv2
import numpy

img = cv2.imread('doctorstrange.jpg',0)
cv2.imwrite('star.jpg',img)
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

3
(2)Write some codes to flip a picture horizontally or vertically.

Rectangle:

import numpy as np
import cv2
my_img = np.zeros((200, 200, 3), dtype = "uint8")

Answer: # creating a rectangle

import cv2 cv2.rectangle(my_img, (30, 30), (300, 200), (255,170,120), 2)


import numpy cv2.imshow('Geometric Graphics (Rectangle)', my_img)

img = cv2.imread('doctorstrange.jpg',cv2.IMREAD_COLOR) # allows us to see image


img = cv2.flip(img,0) #flip # until closed forcefully
cv2.imshow('image',img) cv2.waitKey(0)
cv2.waitKey(0) cv2.destroyAllWindows()
cv2.destroyAllWindows()

(4)Write some codes to implement image mixing blending.


(3)Write some codes to draw some geometries like circular and rectangle.

Ciecle:

import cv2
import numpy as np import cv2
image = np.zeros((200, 200, 3), dtype = "uint8") import numpy as np
img1 = cv2.imread('doctorstrange.jpg')
#Creating circle img2 =cv2.imread('star.jpg')

cv2.circle(image,(300, 300), 150, (255,170,120), 2) dst = cv2.addWeighted(img1, 0.7, img2, 0.3,0)

cv2.imshow('Geometric Graphics (Circle)',image) cv2.imshow('dst',dst)


cv2.waitKey(0) cv2.waitKey(0)
cv2.destroyAllWindows() cd2.destroyAllWindow()

4
Result
Reviewer III、Essay questions(10’×6)

(1) Give a brief explanation of applications of Computer Graphics?

Answer:

5
6
(2)How to use computer graphics knowledge to develop a greedy snake
game and write out design ideas and solutions.
Answer: # game over function
def game_over():

# initial score # creating font object my_font


score = 0 my_font = pygame.font.SysFont('times new roman', 50)
# displaying Score function
def show_score(choice, color, font, size): # creating a text surface on which text
# will be drawn
# creating font object score_font game_over_surface = my_font.render('Your Score is : ' + str(score),
score_font = pygame.font.SysFont(font, size) True, red)

# create the display surface object # create a rectangular object for the text
# score_surface # surface object
score_surface = score_font.render('Score : ' + str(score), True, color) game_over_rect = game_over_surface.get_rect()

# create a rectangular object for the # setting position of the text


# text surface object game_over_rect.midtop = (window_x/2, window_y/4)
score_rect = score_surface.get_rect()
# blit will draw the text on screen
# displaying text game_window.blit(game_over_surface, game_over_rect)
game_window.blit(score_surface, score_rect) pygame.display.flip()

# after 2 seconds we will quit the


# program
-------------------------
time.sleep(2)

# deactivating pygame library


pygame.quit()

# quit the program


quit()

7
(3)Explain the definitions and applications of BGR, HSV,CMYK, YUV color
spaces models.

Answer

8
Code:

import cv2
def videocapture():
cap=cv2.VideoCapture(0)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = cap.get(cv2.CAP_PROP_FPS)
fourcc = int(cap.get(cv2.CAP_PROP_FOURCC))

writer = cv2.VideoWriter("my_Output.mp4", fourcc, fps,


(width, height))
while cap.isOpened():
ret, frame = cap.read()
cv2.imshow('teswell', frame)
key = cv2.waitKey(24)
writer.write(frame)
#press q to quit
if key == ord('q'):
break
cap.release()
cv2.destroyAllWindows()

if __name__ == '__main__' :

(4)How is OpenCV to read and save the video? Write some codes to save videocapture()
the camera video as video file format likes avi, mp4 or flv.
Answer:
In OpenCV, a video can be read either by using the feed from a camera
connected to a computer or by reading a video file. The first step towards
reading a video file is to create a Video Capture object.

In most cases, only one camera is connected to the system. So, all we
do is pass ‘0’ and OpenCV uses the only camera attached to the computer.
When more than one camera is connected to the computer, we can select
the second camera by passing ‘1’, the third camera by passing ‘2’ and
so on.
9
(5)Give at least three geometric transformations of an image, and Translation:
explain the concepts and write some codes to show the results.
Answer: import cv2
import numpy as n
Transformations: img = cv2.imread('piaowei.jpg',0)
OpenCV provides two transformation functions, cv2.warpAffine and rows,cols = img.shape
cv2.warpPerspective, with which you can have all kinds of transformations. M = np.float32([[1,0,100],[0,1,50]])
cv2.warpAffine takes a 2x3 transformation matrix while cv2.warpPerspective takes a dst = cv2.warpAffine(img,M,(cols,rows))
3x3 transformation matrix as input. cv2.imshow('img',dst)
cv2.waitKey(0)
Scaling: cv2.destroyAllWindows()

Scaling is just resizing of the image. OpenCV comes with a function cv2.resize() for
this purpose. The size of the image can be specified manually, or you can specify the
scaling factor. Different interpolation methods are used. Preferable interpolation
methods are cv2.INTER_AREA for shrinking and cv2.INTER_CUBIC (slow) & Result :
cv2.INTER_LINEAR for zooming. By default, interpolation method used is
cv2.INTER_LINEAR for all resizing purposes. You can resize an input image either of
following methods:

Code:

import cv2
import numpy as np
img = cv2.imread('piaowei.jpg')
res = cv2.resize(img,None,fx=2, fy=2, interpolation = cv2.INTER_CUBIC)
#OR
height, width = img.shape[:2]
res = cv2.resize(img,(2*width, 2*height), interpolation =
cv2.INTER_CUBIC)

10
Rotation Affine Transformation

import cv2
import numpy as np import matplotlib.pyplot as plt
img = cv2.imread('piaowei.jpg',0) img = cv2.imread('piaowei.jpg')
rows,cols = img.shape rows,cols,ch = img.shape
M = cv2.getRotationMatrix2D((cols/2,rows/2),90,1) pts1 = np.float32([[50,50],[200,50],[50,200]])
dst = cv2.warpAffine(img,M,(cols,rows)) pts2 = np.float32([[10,100],[200,50],[100,250]])
cv2.imshow('img',dst) M = cv2.getAffineTransform(pts1,pts2)
cv2.waitKey(0) dst = cv2.warpAffine(img,M,(cols,rows))
cv2.destroyAllWindows() plt.subplot(121),plt.imshow(img),plt.title('Input')
plt.subplot(122),plt.imshow(dst),plt.title('Output')
plt.show()

Result: result

11
(6)Explain the concept of working principle of template matching in
OpenCV and write some codes to show the results.

res = cv2.matchTemplate(img,template,method)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
# If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take
minimum
if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
top_left = min_loc
Answer: else:
Template Matching is a method for searching and finding the location of a template top_left = max_loc
image in a larger image. OpenCV comes with a function cv2.matchTemplate() for this bottom_right = (top_left[0] + w, top_left[1] + h)
purpose. It simply slides the template image over the input image (as in 2D convolution) cv2.rectangle(img,top_left, bottom_right, 255, 2)
and compares the template and patch of input image under the template image. Several plt.subplot(121),plt.imshow(res,cmap = 'gray')
comparison methods are implemented in OpenCV. (You can check docs for more plt.title('Matching Result'), plt.xticks([]), plt.yticks([])
details). It returns a grayscale image, where each pixel denotes how much does the plt.subplot(122),plt.imshow(img,cmap = 'gray')
neighbourhood of that pixel match with template. If input image is of size (WxH) and plt.title('Detected Point'), plt.xticks([]), plt.yticks([])
template image is of size (wxh), output image will have a size of (W-w+1, H-h+1). plt.suptitle(meth)
plt.show()
Template Matching in OpenCV :

import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('piaowei.jpg',0)
img2 = img.copy()
template = cv2.imread('head.png',0)
w, h = template.shape[::-1]
# All the 6 methods for comparison in a list
methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED',
'cv2.TM_CCORR',
'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF',
'cv2.TM_SQDIFF_NORMED']
for meth in methods:
img = img2.copy()
method = eval(meth)
# Apply template Matching 12
RESULT:
cv2.TM_CCORR
cv2.TM_CCOEFF

cv2.TM_CCOEFF_NORMED cv2.TM_CCORR_NORMED

13
cv2.TM_SQDIFF

cv2.TM_SQDIFF_NORMED

I can see that the result using cv2.TM_CCORR is not good as we expected.

14

You might also like