[PYTHON] Laplacian Filter experiment

Overview I wanted to detect edges (actually, it's just a color difference rather than an edge), and I was wondering which Laplacian Filter in 4 or 8 directions was better, so I experimented.

Input image ![gray.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/482094/2b678c00-02d5-185b-3ff9-eb5614a0e74b.png)

4-way Laplacian Filter ![img_lap.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/482094/3748afe0-b3dc-dfcb-dfe5-ece09439f834.png)

8-direction Laplacian Filter ![img_lap copy.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/482094/7a69082e-6639-cb43-596d-2f3ed706d6ee.png)

Conclusion Almost the same! Since the result is the same, I would like to use the 8-direction Filter, which seems to have less effect on rotation for the time being.

Code 8 directions 4 directions Please choose your favorite
   def LaplacianLayer(self, img):
        # 4 direction Laplacian
        laplacian_filter = torch.cuda.FloatTensor(
            [[0, 1, 0], [1, -4, 1], [0, 1, 0]]).view(1, 1, 3, 3)
        # 8 direction Laplacian
        # laplacian_filter = torch.cuda.FloatTensor(
        #     [[1, 1, 1], [1, -8, 1], [1, 1, 1]]).view(1, 1, 3, 3)

        gray = self.getGrayImage(img)

        img_lap = torch.nn.functional.conv2d(input=gray,
                                            weight=Variable(laplacian_filter),
                                            stride=1,
                                            padding=0)

        img_lap = torch.abs(img_lap)

        return img_lap

    def getGrayImage(self,rgbImg):
        gray = 0.114*rgbImg[:,0,:,:] + 0.587*rgbImg[:,1,:,:] + 0.299*rgbImg[:,2,:,:]
        gray = torch.unsqueeze(gray,1)
        return gray

References [Image processing] Principles, features, and calculation formulas of Laplacian filters https://algorithm.joho.info/image-processing/laplacian-filter/

Recommended Posts

Laplacian Filter experiment
inspect experiment
svm experiment 1
Edge extraction with python + OpenCV (Sobel filter, Laplacian filter)