# OpenCV_008-OpenCV 中的圖像算術運算

## 目標

• 學習一些圖像的算術運算操作，比如加、減、位運算，等等。

## 圖像加法

def diff_add():
x = np.uint8([250])
y = np.uint8([10])

print(cv.add(x,y)) # 250+10 = 260 => 255
print(x + y)  # 250+10 = 260 % 256 = 4


[[255]]
[4]


## 圖像混合

g(x) = (1 - alpha)f_0(x) + alphaf_1(x)

dst = alpha * img1 + beta * img2 + gamma

def image_blending():
file_ml = cv.samples.findFile('ml.png')

file_logo = cv.samples.findFile('opencv-logo.png')
print(img1.shape)
img2 = cv.resize(img2, (img1.shape[1], img1.shape[0]))
print(img2.shape)
dst = cv.addWeighted(img1, 0.7, img2, 0.3, 0)

plt.subplot(131), plt.imshow(img1, 'gray'), plt.title('ORIGINAL')
plt.subplot(132), plt.imshow(img2, 'gray'), plt.title('REPLICATE')
plt.subplot(133), plt.imshow(dst, 'gray'), plt.title('REFLECT')

plt.show()


def image_blending1():
file_ml = cv.samples.findFile('ml.png')

file_logo = cv.samples.findFile('opencv-logo.png')
print(img1.shape)
img2 = cv.resize(img2, (img1.shape[1], img1.shape[0]))
print(img2.shape)
dst = cv.addWeighted(img1, 0.7, img2, 0.3, 0)

images = [img1, img2, dst]
img4 = cv.hconcat(images)

cv.imshow('Image', img4)
cv.waitKey(0)
cv.destroyAllWindows()


def image_blending2():
file_ml = cv.samples.findFile('ml.png')

file_logo = cv.samples.findFile('opencv-logo.png')
img2 = cv.resize(img2, (img1.shape[1], img1.shape[0]))

weight = 0.01
step = 0.02
while True:
dst = cv.addWeighted(img1, weight, img2, 1 - weight, 0)
cv.imshow('Image', dst)

key = cv.waitKey(35)
if key == ord('q'):
break

weight += step
if (weight > 1.0):
step = -step
elif weight < 0:
step = -step

cv.destroyAllWindows()


## 位操作

def bitwise_operations():

# I want to put logo on top-left corner, So I create a ROI
rows, cols, channels = img2.shape
roi = img1[0:rows, 0:cols]

# Now create a mask of logo and create its inverse mask also
img2gray = cv.cvtColor(img2, cv.COLOR_BGR2GRAY)
ret, mask = cv.threshold(img2gray, 10, 255, cv.THRESH_BINARY)

image = cv.hconcat(images)

# Now black-out the area of logo in ROI

# Take only region of logo from logo image.

# Put logo in ROI and modify the main image

images2 = [img1_bg, img2_fg, dst]
image2 = cv.hconcat(images2)

img1[0:rows, 0:cols] = dst

plt.subplot(212), plt.imshow(image2, 'gray'), plt.title('ROI')

plt.show()


    image4 = np.zeros((img1.shape[0], img2.shape[1], 3), np.uint8)
image4[0:rows, 0:cols] = merged

img1[0:rows, 0:cols] = dst

images5 = [image4, img1]
dest = cv.hconcat(images5)

cv.imshow('res', dest)
cv.waitKey(0)
cv.destroyAllWindows()


## 練習

Arithmetic Operations on Images

OPENCV基礎（三）：圖像的混合

opencv實現幾幅圖像拼接成一整幅大圖

Done.