Junissen
Posted on November 23, 2024
Classification task is the most common in AI because it requires few libraries. I try to write using the resources of an online compiler, without understanding the intricacies of the work.
def rle_decode(mask_rle, shape=(1280, 1918, 1)):
'''
mask_rle: run-length as string formated (start length)
shape: (height,width) of array to return
Returns numpy array, 1 - mask, 0 - background
'''
img = np.zeros(shape[0]*shape[1], dtype=np.uint8)
s = mask_rle.split()
starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])]
starts -= 1
ends = starts + lengths
for lo, hi in zip(starts, ends):
img[lo:hi] = 1
img = img.reshape(shape)
return img
For example, using the function of decoding masks 0/1, you can rely on their lengths. But to generate batch packets of a neural network, you still need to monitor the current results.
def keras_generator(gen_df, batch_size):
while True:
x_batch = []
y_batch = []
for i in range(batch_size):
img_name, mask_rle = gen_df.sample(1).values[0]
img = cv2.imread('data/train/{}'.format(img_name))
mask = rle_decode(mask_rle)
img = cv2.resize(img, (256, 256))
mask = cv2.resize(mask, (256, 256))
x_batch += [img]
y_batch += [mask]
x_batch = np.array(x_batch) / 255.
y_batch = np.array(y_batch)
yield x_batch, np.expand_dims(y_batch, -1)
- I like to put intermediate outputs of the result for eye contact with the code
- If the result doesn't seem to be satisfactory, I edit the previous functions
im_id = 5
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(25, 25))
axes[0].imshow(x[im_id])
axes[1].imshow(pred[im_id, ..., 0] > 0.5)
plt.show()
Output of the result = guaranteed contact with the written code. In this case, exception handling is not needed.
💖 💪 🙅 🚩
Junissen
Posted on November 23, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.