简体   繁体   English

使用循环进行图像分割

[英]Image segmentation with using a loop

I need to do image segmentation using loops.我需要使用循环进行图像分割。 That is, select a coin.即select一枚硬币。 But I have no idea how to do this.但我不知道该怎么做。 Here are my pathetic attempts:这是我可怜的尝试:

import cv2

a=[]

image = cv2.imread(r'E:\coin.jpg')

for line in image:

   for elem in line:
       if elem >=60:
          a.append('1')
       else:
          a.append('0')
cv2.imshow('Gray image', a) 
cv2.waitKey(0)

As a result, I get this error结果,我收到此错误

Traceback (most recent call last):
  File "C:\Users\den22\AppData\Local\Programs\Python\Python36\123.py", line 9, in <module>
    if elem >=60:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Could you please tell me what I'm doing wrong?你能告诉我我做错了什么吗?

You should try to avoid iterating over arrays if you possibly can.如果可能的话,你应该尽量避免迭代 arrays。

import cv2
import numpy as np

image = cv2.imread(r'E:\coin.jpg', cv2.IMREAD_GRAYSCALE)
threshold = 60

binary_mask = np.zeros_like(image)
above_threshold = np.where(image >= 60)
binary_mask[above_threshold] = 1
cv2.imshow(binary_mask)

This shows the logic explicitly, creating an array of zeros and then identifying the values of interest and setting those values in the binary_mask to 1. You can also just plot a boolean array:这明确显示了逻辑,创建一个零数组,然后识别感兴趣的值并将 binary_mask 中的这些值设置为 1。您也可以只 plot 一个 boolean 数组:

bool_array = image >= 60
cv2.imshow(bool_array)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM