Files
pytorch-study/03.ipynb

461 KiB

In [ ]:
from PIL import Image

im = Image.open('data/images/jk.jpg')
im.size
In [ ]:
import numpy as np

im_pillow = np.asarray(im)
im_pillow.shape
In [11]:
!pip install opencv-python
!apt update
!apt install libgl1
Requirement already satisfied: opencv-python in /opt/conda/lib/python3.10/site-packages (4.11.0.86)
Requirement already satisfied: numpy>=1.21.2 in /opt/conda/lib/python3.10/site-packages (from opencv-python) (1.26.3)
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager, possibly rendering your system unusable. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv. Use the --root-user-action option if you know what you are doing and want to suppress this warning.
/usr/bin/sh: 1: sudo: not found
/usr/bin/sh: 1: sudo: not found
In [75]:
import cv2

im_cv2 = cv2.imread('./data/images/jk.jpg')
print(type(im_cv2))

print(im_cv2.shape)
<class 'numpy.ndarray'>
(116, 318, 3)
In [93]:
# 获取对应的RGB通道
im_pillow_c1 = im_pillow[:, :, 0]
im_pillow_c2 = im_pillow[:, :, 1]
im_pillow_c3 = im_pillow[:, :, 2]

print(im_pillow_c1)
[[255 255 255 ... 255 255 255]
 [255 255 255 ... 255 255 255]
 [255 255 255 ... 255 255 255]
 ...
 [255 255 255 ... 255 255 255]
 [255 255 255 ... 255 255 255]
 [255 255 255 ... 255 255 255]]
In [94]:
# 通道调整
zeros = np.zeros((im_pillow_c1.shape[0], im_pillow_c1.shape[1], 1))
zeros.shape
Out[94]:
(116, 318, 1)
In [79]:
im_pillow_c1 = im_pillow_c1[:, :, np.newaxis]
im_pillow_c1.shape
Out[79]:
(116, 318, 1)
In [80]:
im_pillow_c1_3ch = np.concatenate((im_pillow_c1, zeros, zeros), axis=2)
im_pillow_c1_3ch.shape
Out[80]:
(116, 318, 3)
In [106]:
# 方法二调整
im_pillow_c2_3ch = np.zeros(im_pillow.shape)
im_pillow_c2_3ch[:, :, 1] = im_pillow_c2

im_pillow_c3_3ch = np.zeros(im_pillow.shape)
im_pillow_c3_3ch[:, :, 2] = im_pillow_c3

im_pillow_c2_3ch.shape
Out[106]:
(116, 318, 3)
In [107]:
from matplotlib import pyplot as plt

plt.subplot(2, 2, 1)
plt.title('Origin Image')
plt.imshow(im_pillow)
plt.axis('off')

plt.subplot(2, 2, 2)
plt.title('Red Channel')
plt.imshow(im_pillow_c1_3ch.astype(np.uint8))
plt.axis('off')

plt.subplot(2, 2, 3)
plt.title('Green Channel')
plt.imshow(im_pillow_c2_3ch.astype(np.uint8))
plt.axis('off')

plt.subplot(2, 2, 4)
plt.title('Blue Channel')
plt.imshow(im_pillow_c3_3ch.astype(np.uint8))
plt.axis('off')

plt.savefig('./rgb_pillow.png', dpi=150)
No description has been provided for this image
In [108]:
scores = np.random.rand(256, 256, 2)
scores[:,:,1] = 1 - scores[:,:,0]

scores.view()

mask = (scores[:, :, 0] <= scores[:, :, 1]).astype(np.uint8)

import matplotlib.pyplot as plt

plt.imshow(mask, cmap='gray')
plt.title('Mask 0/1 Map')
plt.axis('off')
plt.show()
Out[108]:
(-0.5, 255.5, 255.5, -0.5)
No description has been provided for this image