Converting contours in an image to lines in shapefile using python

Question:

I have processed a screenshot from google maps using OpenCV and identified some contours for the red road sections, and I want to project these contours to a shapefile. I have searched but couldn’t find an answer that followed the same purpose. Here is the screenshot and the contours I found:

I also have the X, Y coordinates of each contour in pixels like the following:

[array([[[271, 485]],
 
        [[271, 488]],
 
        [[272, 489]],
 
        [[272, 491]],
 
        [[273, 492]],
 
        [[274, 492]],
 
        [[273, 492]],
 
        [[272, 491]],
 
        [[272, 489]],
 
        [[271, 488]]], dtype=int32)]

I have been trying to find a way to convert my X, Y coordinates to spatial longitude and latitude and then draw the contour with another library like fiona. I have seen map projections using pyproj geopandas gdal but couldn’t apply any of them to my case. Can you point me in the right direction?

Thanks a lot.

Asked By: ali bbb

||

Answers:

Try the below code and see if it helps:

# Import required modules
import cv2
import os
import shapefile

# Read the image file
img = cv2.imread('path/to/image.jpg')

# Create a new shapefile with lines as the geometry type
w = shapefile.Writer('output_shapefile.shp', shapeType=shapefile.POLYLINE)

# Create fields for the shapefile attributes
w.field('ID', 'N')

# Extract the contours from the image
_, contours, _ = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

# Iterate over the contours and add them as lines to the shapefile
for i, cnt in enumerate(contours):
    w.line(parts=cnt.tolist())
    w.record(i)

# Save the shapefile
w.save()

This code uses the cv2.findContours() method to extract the contours from the image. It then creates a new shapefile using the shapefile module and adds the contours as lines to the shapefile. Finally, it saves the shapefile.

Answered By: ali bakhtiari
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.