opencv 如何在Python中使用Graphcv Segmentation [已关闭]

mo49yndu  于 2023-05-01  发布在  Python
关注(0)|答案(1)|浏览(131)

已关闭,此问题需要更focused。目前不接受答复。
**想改善这个问题吗?**更新问题,使其仅通过editing this post关注一个问题。

2天前关闭。
Improve this question
我找到了下面的cpp示例:
https://github.com/opencv/opencv_contrib/blob/3.1.0/modules/ximgproc/samples/cpp/graphsegmentation_demo.cpp
如何将其转换为Python?

ie3xauqp

ie3xauqp1#

python代码:

import cv2
import numpy as np

# translated from https://github.com/opencv/opencv_contrib/blob/3.1.0/modules/ximgproc/samples/cpp/graphsegmentation_demo.cpp

# write hsv_to_rgb function
def hsv_to_rgb(c):
    in_mat = np.array([[[c[0] * 360, c[1], c[2]]]], dtype=np.float32)
    out_mat = cv2.cvtColor(in_mat, cv2.COLOR_HSV2BGR)
    t = (out_mat * 255).astype(int)
    return tuple(t[0, 0])

  
    

  

def color_mapping(segment_id):
  base = segment_id * 0.618033988749895 + 0.24443434
  return hsv_to_rgb((base % 1.2, 0.95, 0.80))

def doIt(input_image, output_image, sigma=0.5, k=300, min_size=100):
  img = cv2.imread(input_image)
  if not img.data:
    print("Failed to load input image")
    return -3

  # Create a GraphSegmentation object
  gs = cv2.ximgproc.segmentation.createGraphSegmentation()

  # Set the sigma, k, and min_size parameters
  gs.setSigma(sigma)
  gs.setK(k)
  gs.setMinSize(min_size)

  # Process the image
  segments = gs.processImage(img)

  # Get the minimum and maximum values in the segments image
  # min, max,_, _ = cv2.minMaxLoc(segments)

  # # Get the number of segments
  # nb_segs = int(max + 1)

  # Create an output image
  output = np.zeros_like(img)
  for segment_id in np.unique(segments):
      output[segments == segment_id] = color_mapping(segment_id)

  # Save the output image
  cv2.imwrite(output_image, output)

  print("Image written to " + output_image)

  return 0

pathImg = f'/Users/eliaweiss/Documents/doc2txt/tables/ramatgan.jpg'
pathOutput = f'result/segmented.jpg'

def main():
    doIt(pathImg,pathOutput, sigma=0.05, k=300, min_size=1000)

相关问题