reformat image to target shape :param data: image data as numpy array :param dst_shape: target shape
(path, data, dst_shape)
| 772 | input_transform, |
| 773 | ): |
| 774 | def auto_reformat_image(path, data, dst_shape): |
| 775 | """reformat image to target shape |
| 776 | |
| 777 | :param data: image data as numpy array |
| 778 | :param dst_shape: target shape |
| 779 | """ |
| 780 | dim3_format = False # required input format does not contain batch |
| 781 | hwc_format = False # required input format is NHWC |
| 782 | |
| 783 | if not dst_shape: # input tensor shape is not predefined |
| 784 | if len(data.shape) == 2: |
| 785 | chl = 1 |
| 786 | h = data.shape[0] |
| 787 | w = data.shape[1] |
| 788 | else: |
| 789 | assert ( |
| 790 | len(data.shape) == 3 |
| 791 | ), "Input image must be of dimension 2 or 3" |
| 792 | h, w, chl = data.shape |
| 793 | dst_shape = (1, chl, h, w) |
| 794 | |
| 795 | if len(dst_shape) == 3: |
| 796 | dst_shape = (1,) + dst_shape |
| 797 | dim3_format = True |
| 798 | |
| 799 | assert len(dst_shape) == 4, "bad dst_shape: {}".format(dst_shape) |
| 800 | chl = dst_shape[1] |
| 801 | if chl in [1, 3]: |
| 802 | n, c, h, w = dst_shape |
| 803 | dst_shape = (n, h, w, c) |
| 804 | else: |
| 805 | chl = dst_shape[3] |
| 806 | assert chl in [ |
| 807 | 1, |
| 808 | 3, |
| 809 | ], "can not infer input format from shape: {}".format(dst_shape) |
| 810 | hwc_format = True |
| 811 | |
| 812 | # dst_shape has now been normalized to NHWC format |
| 813 | |
| 814 | if resize_input: |
| 815 | h, w = dst_shape[1:3] |
| 816 | data = cv2.resize(data, (w, h)) |
| 817 | logger.info("input {} resized to {}".format(path, data.shape)) |
| 818 | |
| 819 | if chl == 1: |
| 820 | data = cv2.cvtColor(data, cv2.COLOR_BGR2GRAY) |
| 821 | data = data[:, :, np.newaxis] |
| 822 | |
| 823 | assert data.ndim == 3 |
| 824 | data = data[np.newaxis] |
| 825 | # data normalized to NHWC format |
| 826 | |
| 827 | if not hwc_format: |
| 828 | data = np.transpose(data, (0, 3, 1, 2)) |
| 829 | |
| 830 | if dim3_format: |
| 831 | data = np.squeeze(data, 0) |