ndi图像处理

The model itself is written in keras, but to prepare vector labels I used scipy.ndimage.morphology

scipy.ndimage.morphology.distance_transform_edt() is very useful to find distance and direction to the border as it can return the index of the nearest pixel outside of mask:

edt, inds = scipy.ndimage.morphology.distance_transform_edt(crop_smooth, return_distances=True, return_indices=True)
border_vector = np.array([
    np.expand_dims(np.arange(0, rows), axis=1) - inds[0],
    np.expand_dims(np.arange(0, cols), axis=0) - inds[1]])

border_vector_norm = border_vector / (np.linalg.norm(border_vector, axis=0, keepdims=True) + 1e-5)
res_crop[:, :, 0] = border_vector_norm[0]
res_crop[:, :, 1] = border_vector_norm[1]

Vector to the center is easier to calculate, it's a difference of the pixel position and the mask center of mass:

 center_of_mass = scipy.ndimage.measurements.center_of_mass(crop)
 current_offset_field = np.zeros((CROP_SIZE, CROP_SIZE, 2))
 current_offset_field[:, :, 0] = np.expand_dims(center_of_mass[0] - np.arange(0, CROP_SIZE), axis=1)
 current_offset_field[:, :, 1] = np.expand_dims(center_of_mass[1] - np.arange(0, CROP_SIZE), axis=0)
### 数字图像处理的 Python 代码示例 以下是几个基于 OpenCV 和 PIL 的数字图像处理代码示例: #### 示例 1: 使用 OpenCV 进行灰度转换 ```python import cv2 # 读取彩色图像 img = cv2.imread('example.jpg') # 将图像转换为灰度图像 gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 显示原始图像和灰度图像 cv2.imshow('Original Image', img) cv2.imshow('Grayscale Image', gray_img) cv2.waitKey(0) cv2.destroyAllWindows() ``` 这段代码展示了如何使用 OpenCV 将彩色图像转换为灰度图像[^1]。 --- #### 示例 2: 使用 PIL 绘制中文字符到图像上 ```python from PIL import Image, ImageFont, ImageDraw import numpy as np import cv2 def paint_chinese_opencv(im, chinese, pos, color): # 将 OpenCV 图像转换为 PIL 图像 img_PIL = Image.fromarray(cv2.cvtColor(im, cv2.COLOR_BGR2RGB)) # 加载中文字体文件 font = ImageFont.truetype('NotoSansCJKsc-Medium.otf', 25) # 创建绘图对象并设置字体颜色 draw = ImageDraw.Draw(img_PIL) draw.text(pos, chinese, font=font, fill=color) # 转换回 OpenCV 格式 img = cv2.cvtColor(np.asarray(img_PIL), cv2.COLOR_RGB2BGR) return img # 测试函数 img = cv2.imread('example.jpg') result = paint_chinese_opencv(img, '你好世界', (100, 100), (255, 255, 0)) # 展示结果 cv2.imshow('Result', result) cv2.waitKey(0) cv2.destroyAllWindows() ``` 该代码片段演示了如何通过 PIL 库在图像上绘制中文字符,并将其与 OpenCV 结合使用[^2]。 --- #### 示例 3: 使用 NumPy 实现图像旋转 ```python import numpy as np import matplotlib.pyplot as plt def rotation_matrix(theta): """生成二维平面内的旋转矩阵""" return np.array([ [np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)] ]) # 读取图像 image = plt.imread('lena.png') # 获取图像的高度和宽度 height, width = image.shape[:2] # 构建网格坐标系 y, x = np.mgrid[:height, :width] coords = np.column_stack([x.ravel(), y.ravel()]) # 应用旋转矩阵 theta = np.radians(45) # 顺时针旋转 45° rotated_coords = coords @ rotation_matrix(-theta).T # 插值获取新位置的颜色值 new_x, new_y = rotated_coords[:, 0].reshape(height, width), \ rotated_coords[:, 1].reshape(height, width) rotated_image = np.zeros_like(image) for c in range(image.shape[-1]): rotated_image[..., c] = np.interp(new_x.flatten(), np.arange(width), image[..., c].flatten()).reshape(height, width) plt.imshow(rotated_image.clip(0, 255).astype(np.uint8)) plt.axis('off') plt.show() ``` 这个例子说明了如何利用 NumPy 和 Matplotlib 来实现图像的几何变换(如旋转),并通过插值算法完成像素映射[^3]。 --- #### 示例 4: 不同库之间的图像读取比较 ```python import cv2 from skimage import io as skio import scipy.ndimage as ndi # 使用 OpenCV 读取图像 opencv_img = cv2.imread('example.jpg') # 默认通道顺序为 BGR # 使用 scikit-image 读取图像 skimage_img = skio.imread('example.jpg') # 默认通道顺序为 RGB # 使用 SciPy 读取图像 scipy_img = ndi.imread('example.jpg') # 返回的是 ndarray,通道顺序为 RGB print(f'OpenCV Shape: {opencv_img.shape}, Channel Order: BGR') print(f'Scikit-Image Shape: {skimage_img.shape}, Channel Order: RGB') print(f'SciPy Shape: {scipy_img.shape}, Channel Order: RGB') ``` 以上代码对比了几种常用库(OpenCV、Scikit-Image 和 SciPy)在读取图像时的行为差异[^4]。 --- #### 示例 5: Pygame 中精灵类的应用 ```python import pygame class Player(pygame.sprite.Sprite): def __init__(self, image_path, position): super().__init__() self.image = pygame.image.load(image_path).convert_alpha() self.rect = self.image.get_rect(topleft=position) def update(self): keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: self.rect.x -= 5 elif keys[pygame.K_RIGHT]: self.rect.x += 5 screen = pygame.display.set_mode((800, 600)) player = Player('character.png', (400, 300)) group = pygame.sprite.Group(player) running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False group.update() screen.fill((0, 0, 0)) group.draw(screen) pygame.display.flip() pygame.quit() ``` 这是一个简单的游戏开发案例,展示如何使用 Pygame 的 `Sprite` 类来管理游戏角色及其动画[^5]。 --- ### 总结 这些代码涵盖了从基础操作(如灰度化、旋转)到高级功能(如文本渲染、跨库兼容性和游戏开发)的各种场景。每一段代码都针对特定需求进行了优化设计。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值