<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>Code on JhuoW‘s Notes</title>
    <link>https://JhuoW.github.io/categories/code/</link>
    <description>Recent content in Code on JhuoW‘s Notes</description>
    <image>
      <url>https://JhuoW.github.io/%3Clink%20or%20path%20of%20image%20for%20opengraph,%20twitter-cards%3E</url>
      <link>https://JhuoW.github.io/%3Clink%20or%20path%20of%20image%20for%20opengraph,%20twitter-cards%3E</link>
    </image>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <lastBuildDate>Sun, 27 Mar 2022 15:38:50 +0800</lastBuildDate><atom:link href="https://JhuoW.github.io/categories/code/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>Awesome Barbell Graph with Networkx</title>
      <link>https://JhuoW.github.io/posts/barbell_graph/</link>
      <pubDate>Sun, 27 Mar 2022 15:38:50 +0800</pubDate>
      
      <guid>https://JhuoW.github.io/posts/barbell_graph/</guid>
      <description>&lt;h3 id=&#34;晕了&#34;&gt;晕了&lt;/h3&gt;
&lt;pre tabindex=&#34;0&#34;&gt;&lt;code&gt;import networkx as nx
import matplotlib.pyplot as plt

n_clique, n_path = 10, 10
clique1 = nx.complete_graph(n_clique)
clique1_pos = nx.circular_layout(clique1)
clique2 = nx.complete_graph(n_clique)
clique2_mapping = {node: node + n_clique for node in clique2}
nx.relabel_nodes(clique2, clique2_mapping, copy=False) # avoids repeated nodes
x_diff, y_diff = 8, -1
clique2_pos = {node: clique1_pos[node-n_clique] + (x_diff, y_diff) for node in clique2}
path = nx.path_graph(n_path)
path_mapping = {node: node + 2 * n_clique for node in path}
nx.relabel_nodes(path, path_mapping, copy=False) # avoids repeated nodes
path_nodes = list(path.nodes)
path_half1_nodes = path_nodes[:n_path//2]
path_half2_nodes = path_nodes[n_path//2:]
path_dist = 0.9
clique2_entry = n_clique + n_clique // 2
path_half1_pos = {node: clique1_pos[0] + (path_dist + i * path_dist, 0) for i, node in enumerate(path_half1_nodes)}
path_half2_pos = {node: clique2_pos[clique2_entry] - (path_dist + i * path_dist, 0) for i, node in enumerate(path_half2_nodes[::-1])}
path_pos = {**path_half1_pos, **path_half2_pos}
barbell = nx.Graph()
barbell.add_edges_from(clique1.edges)
barbell.add_edges_from(clique2.edges)
barbell.add_edges_from(path.edges)
barbell.add_edges_from([(path_half1_nodes[0], 0), (path_half2_nodes[-1], clique2_entry)])
clique_pos = {**clique1_pos, **clique2_pos}
barbell_pos = {**clique_pos, **path_pos}
plt.figure(figsize=(20, 6))
nx.draw(barbell, pos=barbell_pos, with_labels=True)
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;&lt;img loading=&#34;lazy&#34; src=&#34;https://JhuoW.github.io/posts/barbell-graph/barbell.png#center&#34; alt=&#34;你想输入的替代文字&#34;  /&gt;
&lt;/p&gt;</description>
      <content:encoded><![CDATA[<h3 id="晕了">晕了</h3>
<pre tabindex="0"><code>import networkx as nx
import matplotlib.pyplot as plt

n_clique, n_path = 10, 10
clique1 = nx.complete_graph(n_clique)
clique1_pos = nx.circular_layout(clique1)
clique2 = nx.complete_graph(n_clique)
clique2_mapping = {node: node + n_clique for node in clique2}
nx.relabel_nodes(clique2, clique2_mapping, copy=False) # avoids repeated nodes
x_diff, y_diff = 8, -1
clique2_pos = {node: clique1_pos[node-n_clique] + (x_diff, y_diff) for node in clique2}
path = nx.path_graph(n_path)
path_mapping = {node: node + 2 * n_clique for node in path}
nx.relabel_nodes(path, path_mapping, copy=False) # avoids repeated nodes
path_nodes = list(path.nodes)
path_half1_nodes = path_nodes[:n_path//2]
path_half2_nodes = path_nodes[n_path//2:]
path_dist = 0.9
clique2_entry = n_clique + n_clique // 2
path_half1_pos = {node: clique1_pos[0] + (path_dist + i * path_dist, 0) for i, node in enumerate(path_half1_nodes)}
path_half2_pos = {node: clique2_pos[clique2_entry] - (path_dist + i * path_dist, 0) for i, node in enumerate(path_half2_nodes[::-1])}
path_pos = {**path_half1_pos, **path_half2_pos}
barbell = nx.Graph()
barbell.add_edges_from(clique1.edges)
barbell.add_edges_from(clique2.edges)
barbell.add_edges_from(path.edges)
barbell.add_edges_from([(path_half1_nodes[0], 0), (path_half2_nodes[-1], clique2_entry)])
clique_pos = {**clique1_pos, **clique2_pos}
barbell_pos = {**clique_pos, **path_pos}
plt.figure(figsize=(20, 6))
nx.draw(barbell, pos=barbell_pos, with_labels=True)
</code></pre><p><img loading="lazy" src="/posts/barbell-graph/barbell.png#center" alt="你想输入的替代文字"  />
</p>
]]></content:encoded>
    </item>
    
    <item>
      <title>OpenCV轮廓提取并计算图片中某一封闭区域的面积</title>
      <link>https://JhuoW.github.io/posts/pic-closed-edge/</link>
      <pubDate>Mon, 02 Apr 2018 15:43:44 +0000</pubDate>
      
      <guid>https://JhuoW.github.io/posts/pic-closed-edge/</guid>
      <description>&lt;p&gt;最近遇到一个问题，如果需要计算区域内的面积，比如说要计算下图中类似三角形区域内的面积&lt;br&gt;
&lt;img loading=&#34;lazy&#34; src=&#34;https://JhuoW.github.io/posts/2019-04-02-Pic-closed-edge/1.png&#34; alt=&#34;&#34;  /&gt;
&lt;br&gt;
之前的做法是用Canny算子提取边缘，再用HoughLines拟合直线，然后求出交点坐标并计算三角形面积，其中，边缘提取后的图像如下图所示：&lt;br&gt;
&lt;img loading=&#34;lazy&#34; src=&#34;https://JhuoW.github.io/posts/2019-04-02-Pic-closed-edge/edge.jpeg&#34; alt=&#34;&#34;  /&gt;
&lt;br&gt;
我们可以很明显的看出这不是一个标准的三角形，所以如果想要更精确的获得三角形，就需要对图片进行轮廓提取，然后计算轮廓内区域的面积。这里给出代码：&lt;br&gt;
{% codeblock %}&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import cv2
import numpy as np

# Input image
img = cv2.imread(&#39;cut.jpeg&#39;, cv2.IMREAD_GRAYSCALE)

# Needed due to JPG artifacts
_, temp = cv2.threshold(img, 128, 255, cv2.THRESH_BINARY)

# Dilate to better detect contours
temp = cv2.dilate(temp, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)))

# Find largest contour
_, cnts, _ = cv2.findContours(temp, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
largestCnt = []
for cnt in cnts:
    if len(cnt) &amp;gt; len(largestCnt):
        largestCnt = cnt

# Determine center of area of largest contour
M = cv2.moments(largestCnt)
x = int(M[&amp;quot;m10&amp;quot;] / M[&amp;quot;m00&amp;quot;])
y = int(M[&amp;quot;m01&amp;quot;] / M[&amp;quot;m00&amp;quot;])

# Initiale mask for flood filling
width, height = temp.shape
mask = img2 = np.ones((width + 2, height + 2), np.uint8) * 255
mask[1:width, 1:height] = 0

# Generate intermediate image, draw largest contour, flood filled
temp = np.zeros(temp.shape, np.uint8)
temp = cv2.drawContours(temp, largestCnt, -1, 255, cv2.FILLED)
_, temp, mask, _ = cv2.floodFill(temp, mask, (x, y), 255)
temp = cv2.morphologyEx(temp, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)))

# Count pixels in desired region
area = cv2.countNonZero(temp)

# Put result on original image
img = cv2.putText(img, str(area), (x, y), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, 255)

cv2.imshow(&#39;Input&#39;, img)
cv2.imshow(&#39;Temp image&#39;, temp)

cv2.waitKey(0)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;{% endcodeblock %}&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>最近遇到一个问题，如果需要计算区域内的面积，比如说要计算下图中类似三角形区域内的面积<br>
<img loading="lazy" src="/posts/2019-04-02-Pic-closed-edge/1.png" alt=""  />
<br>
之前的做法是用Canny算子提取边缘，再用HoughLines拟合直线，然后求出交点坐标并计算三角形面积，其中，边缘提取后的图像如下图所示：<br>
<img loading="lazy" src="/posts/2019-04-02-Pic-closed-edge/edge.jpeg" alt=""  />
<br>
我们可以很明显的看出这不是一个标准的三角形，所以如果想要更精确的获得三角形，就需要对图片进行轮廓提取，然后计算轮廓内区域的面积。这里给出代码：<br>
{% codeblock %}</p>
<pre><code>import cv2
import numpy as np

# Input image
img = cv2.imread('cut.jpeg', cv2.IMREAD_GRAYSCALE)

# Needed due to JPG artifacts
_, temp = cv2.threshold(img, 128, 255, cv2.THRESH_BINARY)

# Dilate to better detect contours
temp = cv2.dilate(temp, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)))

# Find largest contour
_, cnts, _ = cv2.findContours(temp, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
largestCnt = []
for cnt in cnts:
    if len(cnt) &gt; len(largestCnt):
        largestCnt = cnt

# Determine center of area of largest contour
M = cv2.moments(largestCnt)
x = int(M[&quot;m10&quot;] / M[&quot;m00&quot;])
y = int(M[&quot;m01&quot;] / M[&quot;m00&quot;])

# Initiale mask for flood filling
width, height = temp.shape
mask = img2 = np.ones((width + 2, height + 2), np.uint8) * 255
mask[1:width, 1:height] = 0

# Generate intermediate image, draw largest contour, flood filled
temp = np.zeros(temp.shape, np.uint8)
temp = cv2.drawContours(temp, largestCnt, -1, 255, cv2.FILLED)
_, temp, mask, _ = cv2.floodFill(temp, mask, (x, y), 255)
temp = cv2.morphologyEx(temp, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)))

# Count pixels in desired region
area = cv2.countNonZero(temp)

# Put result on original image
img = cv2.putText(img, str(area), (x, y), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, 255)

cv2.imshow('Input', img)
cv2.imshow('Temp image', temp)

cv2.waitKey(0)
</code></pre>
<p>{% endcodeblock %}</p>
<p>最后我们可以得到一个比较准确的轮廓：<br>
<img loading="lazy" src="/posts/2019-04-02-Pic-closed-edge/img_trk.jpg" alt=""  />
<br>
面积如图中所示：<br>
<img loading="lazy" src="/posts/2019-04-02-Pic-closed-edge/img_tr.jpg" alt=""  />
</p>
<p>参考：<br>
<a href="https://stackoverflow.com/questions/55467031/how-to-get-the-area-of-the-contours">https://stackoverflow.com/questions/55467031/how-to-get-the-area-of-the-contours</a></p>
]]></content:encoded>
    </item>
    
  </channel>
</rss>
