<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jeffrey on Medium]]></title>
        <description><![CDATA[Stories by Jeffrey on Medium]]></description>
        <link>https://medium.com/@b10932006?source=rss-c7e6b810b895------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*jUequpYZyWHq6zEB</url>
            <title>Stories by Jeffrey on Medium</title>
            <link>https://medium.com/@b10932006?source=rss-c7e6b810b895------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 10:37:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@b10932006/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Algorithm introduction — XGboost]]></title>
            <link>https://medium.com/ntust-aivc/algorithm-introduction-xgboost-622f1293d80f?source=rss-c7e6b810b895------2</link>
            <guid isPermaLink="false">https://medium.com/p/622f1293d80f</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[boosting]]></category>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[artifact]]></category>
            <dc:creator><![CDATA[Jeffrey]]></dc:creator>
            <pubDate>Tue, 21 Mar 2023 16:02:10 GMT</pubDate>
            <atom:updated>2023-03-21T16:02:10.536Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5QexLWX1X_kIxnRU6wXAyA.png" /></figure><h3>Algorithm introduction — XGboost</h3><p>Kaggle Competition Artifacts You Must Know</p><h3>Prolegomenon</h3><p>If you are looking for an<strong> efficient</strong>, <strong>accurate</strong>, and <strong>reliable </strong>machine learning algorithm, then XGBoost may be your best choice. XGBoost is a <strong>supervised learning algorithm</strong> that builds a powerful integrated learning model by iteratively training multiple weak classifiers. It has the characteristics of strong scalability, fast speed, and high accuracy and also <strong>supports multiple loss functions and objective functions</strong>. It can be applied to <strong>various application scenarios</strong> such as <strong>regression and classification</strong>. Due to its outstanding performance, it has achieved excellent results in many machine learning competitions and has become <strong>one of the indispensable algorithms </strong>in machine learning.</p><h3>Contents</h3><p><a href="#3afe">Prolegomenon</a><br><a href="#b727">Boosting? Gradient Boosting?<br></a><a href="#3bff">XGBOOST?</a><br><a href="#56ea">Features</a><br><a href="#1cad">Algorithm Introduction</a><br><a href="#5713">Program API</a><br><a href="#c756">mathematical algorithm</a><br><a href="#dd72">Done!</a><br><a href="#137f">References</a></p><h3>Boosting? Gradient Boosting?</h3><p><strong>XGBoost</strong>, also known as <strong>eXtreme Gradient Boosting</strong>, is a<strong> gradient boosting algorithm</strong>, so before introducing XGBOOST we must first understand what Boosting and Gradient Boosting are.</p><p><strong>Boosting</strong> is an algorithm that combines multiple<strong> weak classifiers</strong> (such as decision trees) into <strong>one strong classifier</strong>. It gradually adjusts the weight of each weak classifier to<strong> pay more attention to misclassified samples</strong>, thereby improving classification accuracy, but it is also prone to overfitting.</p><p><strong>Gradient Boosting</strong> is a Boosting algorithm optimized using <strong>the gradient descent algorithm</strong>. In the Gradient Boosting algorithm, each new weak classifier is trained based on<strong> the residuals of the previous classifiers</strong> (i.e. the difference between the true value and the current model prediction). The prediction accuracy of the model is further improved by optimizing the residuals of the previous weak classifiers using the gradient descent algorithm.</p><h3>XGBOOST?</h3><p><strong>eXtreme Gradient Boosting</strong> is a <strong>gradient boosting algorithm</strong> originally developed by Dr. Chen Tianqi in 2016. It is an extended version of the gradient boosting algorithm that <strong>achieves superior performance on classification and regression problems</strong>. It uses <strong>regularization techniques</strong> to improve the predictive accuracy of the model while avoiding the problem of overfitting. XGBoost can also <strong>automatically handle missing values and categorical features</strong>, which makes using XGBoost easier and faster. It is also <strong>very scalable</strong> and <strong>supports multiple program languages</strong>, including Python, R, Java, and Scala. In machine learning competitions, XGBoost is <strong>widely used</strong> and has <strong>achieved many excellent results</strong>.</p><h3>Features</h3><p>Compared with other machine learning algorithms, XGBoost has the following characteristics:</p><ul><li><strong>Efficiency</strong>: XGBoost uses <strong>parallelization technology</strong> to quickly process large-scale data sets.</li><li><strong>Scalability</strong>: XGBoost can run in <strong>various environments</strong>, including distributed environments and Hadoop clusters.</li><li><strong>Accuracy</strong>: XGBoost uses <strong>a gradient boosting algorithm and regularization technology</strong> to get more accurate prediction results.</li><li><strong>Interpretability</strong>: XGBoost can provide <strong>feature importance rankings</strong>, making it easier for users to understand how the model works.</li><li><strong>Flexibility</strong>: XGBoost can be used for <strong>regression problems, classification problems, and ranking problems</strong>, as well as <strong>multiple scenarios</strong> such as multi-objective learning and hybrid learning.</li></ul><p>In addition, XGBoost also provides <strong>a wealth of parameter configuration options</strong>, users can adjust according to their own needs to obtain the best performance.</p><h3>Algorithm Introduction</h3><p>XGBoost uses the following algorithms:</p><ol><li><strong>Gradient Boosting algorithm</strong>: This was introduced earlier.</li><li><strong>Classification and Regression Trees algorithm</strong> (CART): The CART algorithm is a <strong>decision tree algorithm</strong> for classification and regression problems. XGBoost <strong>uses the CART algorithm as its weak classifier</strong>. Each CART is composed of a binary tree, and samples are assigned to different subtrees according to the value of the feature.</li><li><strong>Regularization</strong>: In order to <strong>prevent overfitting</strong>, XGBoost uses <strong>regularization techniques</strong>, including L1 regularization and L2 regularization. These techniques limit the complexity of the model by <strong>adding penalty terms</strong> to avoid the problem of overfitting.</li><li><strong>Adaptive Learning Rate</strong>: XGBoost uses adaptive learning rate technology, which can <strong>dynamically adjust the learning rate</strong> according to the model&#39;s performance. When <strong>the model performs well</strong>, the <strong>learning rate is reduced</strong> to avoid overfitting; when <strong>the model performs poorly</strong>, <strong>the learning rate is increased</strong> to speed up convergence.</li></ol><p>In short, XGBoost uses <strong>the gradient boosting algorithm and regularization technology</strong> and uses<strong> the CART algorithm</strong> as its weak classifier to gradually build a more powerful integrated learning model. It also uses <strong>adaptive learning rate technology</strong> to optimize the learning process to improve training efficiency and accuracy.</p><h3>Program API</h3><p>Before starting to analyze the detailed operation method inside, let’s take a look at <strong>what parameters need</strong> to be given to XGBOOST when using it. For details, please refer to <a href="https://xgboost.readthedocs.io/en/stable/python/python_api.html">the official website</a>.</p><h4><strong>class xgboost.XGBRegressor</strong></h4><p><strong>Parameters</strong>:</p><ul><li><strong>n_estimators</strong>: Number of gradient boosted trees. Equivalent to the number of boosting rounds. The default value is 100.</li><li><strong>max_depth</strong>: Maximum tree depth for base learners. The default value is 6.</li><li><strong>booster</strong>: Specify which booster to use: gbtree, gblinear, or dart.</li><li><strong>learning_rate</strong>: Boosting learning rate, default 0.3.</li><li><strong>gamma</strong>: Minimum loss reduction required to make a further partition on a leaf node of the tree.</li></ul><p><strong>Methods</strong>:</p><ul><li><strong>fit</strong>: Put in X and Y for model fitting.</li><li><strong>predict</strong>: Predict with X and return the predicted category.</li><li><strong>score</strong>: Return the coefficient of determination of the prediction.</li><li><strong>predict_proba</strong>: Predict the probability of each X example being of a given class.</li></ul><h3>mathematical algorithm</h3><p>Finally, let’s talk about how XGBOOST calculates in mathematics.<br>Specifically, the objective function of XGBOOST consists of two parts: <strong>a loss function and a regularization term</strong>, which can be expressed by the following formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*rRvGKLoSYW7PvMPNiDDF1A.png" /></figure><p>Among them, L(y, ŷ) is the loss function, y is the real value, ŷ is the predicted value of the model; Ω(w) is the regularization item, w is the model parameter; λ is the regularization coefficient.<br>In the process of optimizing the objective function, XGBOOST uses the information of <strong>the first-order gradient</strong> and <strong>the second-order gradient</strong> to calculate the weight of each sample, and then build a decision tree. Specifically, for the i-th sample in the t-th iteration, its weight w(t, i) can be calculated by the following formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*tyQu-Q3asKUb1LKU_djS2g.png" /></figure><p>Among them, g(i) is the first-order differential gradient of the i-th sample, h(i) is the second-order differential gradient of the i-th sample, and λ is the regularization coefficient.<br>When constructing the decision tree, XGBOOST adopts some optimization techniques, such as sorting by feature, splitting by feature, etc., to improve the training speed and accuracy of the model. Ultimately, XGBOOST combines multiple decision trees to form a powerful ensemble model for complex classification and regression problems.</p><h3>Done!</h3><p>Now if you can go try to do it by yourself, you would learn more about it. Thanks for your watching, If you like my article don’t forget to leave your clap or share it with your friend. Your appreciation is my motivation.<br> — Jeffrey</p><h3>References</h3><ul><li><a href="https://medium.com/chung-yi/xgboost%E4%BB%8B%E7%B4%B9-b31f7ec8295e">XGBoost介紹</a></li><li><a href="https://medium.com/@pahome.chen/xgboost%E5%85%A5%E9%96%80%E7%B6%93%E9%A9%97%E5%88%86%E4%BA%AB-e06931b835f5">XGboost入門經驗分享</a></li><li><a href="https://medium.com/@cwchang/gradient-boosting-%E7%B0%A1%E4%BB%8B-f3a578ae7205">Gradient Boosting 簡介</a></li><li><a href="https://ithelp.ithome.com.tw/articles/10273094">[Day 15] 機器學習常勝軍 - XGBoost - iT 邦幫忙::一起幫忙解決難題，拯救 IT 人的一天</a></li><li><a href="https://zhuanlan.zhihu.com/p/38329631">集成学习之Boosting -- Gradient Boosting原理</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=622f1293d80f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ntust-aivc/algorithm-introduction-xgboost-622f1293d80f">Algorithm introduction — XGboost</a> was originally published in <a href="https://medium.com/ntust-aivc">NTUST-AIVC</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Digital Image Processing : Edge Detection]]></title>
            <link>https://medium.com/ntust-aivc/digital-image-processing-edge-detection-29aa84a8fd60?source=rss-c7e6b810b895------2</link>
            <guid isPermaLink="false">https://medium.com/p/29aa84a8fd60</guid>
            <category><![CDATA[digital-image-processing]]></category>
            <category><![CDATA[edge-detection]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[opencv]]></category>
            <dc:creator><![CDATA[Jeffrey]]></dc:creator>
            <pubDate>Wed, 31 Aug 2022 04:42:36 GMT</pubDate>
            <atom:updated>2022-09-16T05:18:36.521Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cj8DT8wjZkpNjpJxaMnHEw.png" /></figure><h3>Digital Image Processing: Edge Detection</h3><p>Use openCV’s built-in Sobal and Laplacian to find the edge of the graph.</p><h3>Prolegomenon</h3><p>In the previous articles, I introduced the <a href="https://medium.com/ntust-aivc/opencv-fourier-transform-d9811aaac2d5">Fourier Transform</a>, this time I will introduce another image processing method, <strong>edge detection</strong>. In openCV, there are many functions that allow us to find the edge of the image, and in this article, I will pick out the more representative <strong>Sobal operators </strong>and <strong>Laplacian operators </strong>for the introduction.</p><h3>Contents</h3><p><a href="#0d56">Prolegomenon</a><br><a href="#dcbf">Edge detection</a><br><a href="#5010">Laplacian operator</a><br><a href="#3d12">Sobal operator</a><br><a href="#327e">Done!</a><br><a href="#1187">References</a></p><h3>Edge detection</h3><p>Since we want to detect the edge, first we need to understand <strong>what the edge is</strong>?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*8pbV2zGNtK2gXcP3.jpg" /><figcaption>the easiest edge</figcaption></figure><p>Take the picture above as an example, we can see that the boundary between black and white is the edge we are looking for, that is, <strong>the sharp change between pixels</strong>.</p><h3>Laplacian operator</h3><h4>principle</h4><p>The Laplacian operator uses the method of <strong>differentiating the image</strong> to extract the edge. The specific derivation method is as follows.</p><p>Take a picture similar to the front as an example, take one of the horizontal lines and differentiate it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*H4ErkCZ6_swsGJHBD1DbNQ.png" /><figcaption>(f) is the value of the image. (f’) the first-order differential of f. (f’’) the second-order differential of f.</figcaption></figure><p>It can be seen that at the junction of the edges, after a differentiation, there will be <strong>an obvious peak</strong>. We can set a threshold so that if the image after a differentiation exceeds this threshold, it will be judged as an edge, and subsequent processing will be performed.</p><p>However, this method is not rigorous enough, so the image can also be differentiated twice. And the Z point in the second derivative result, that is, “<strong>Zero-crossing</strong>”, is the edge we are looking for.</p><p>After understanding the basic principles, we need to mathematically deduce what the mask required by Laplacian should look like. From the above introduction, it can be seen that the most important part is to differentiate the image, but in fact, this is not difficult in the image, just <strong>subtract the pixels of the previous grid from the pixels of the next grid</strong>, that is The slope, which is the first derivative, can be obtained.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*67Se2vz08wbTRDrgv3WJKQ.png" /><figcaption>mathematical expression</figcaption></figure><p>After knowing how to derive the first-order differential, the second-order differential can also be derived in a similar way. Here, we will skip the derivation process and see the results directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*f2ZlTGmOyF-VcmZBMra2Jg.png" /><figcaption>The mathematical formula for second order differential</figcaption></figure><p>At this point, we got the Laplacian mask we need.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/203/1*ipAQNxvEk0EOvSN5RCA2qQ.png" /><figcaption>Laplacian operator mask</figcaption></figure><h4>Implement</h4><p>We can use the Laplacian operation function provided in openCV:</p><pre>dst = cv2.Laplacian(src, ddepth, ksize)</pre><blockquote><em>src : the image to be processed.<br></em><em>dst : output image.<br></em><em>ddepth : The depth of the image. There are many flags that can be used. The most commonly used ones are </em><em>cv2.CV_8U and </em><em>cv2.CV_16S.<br></em><em>ksize : the size of the mask.</em></blockquote><h4>Sample program</h4><p>The specific code can be viewed on <a href="https://github.com/jeffrey0524/AAA/tree/main/article05">my github</a>.</p><pre>import cv2</pre><pre>def main():<br> # read image<br> gray_img = cv2.imread(&quot;./lenna.jpg&quot;, 0)<br> cv2.imshow(&quot;img&quot;,gray_img)</pre><pre># Try masks of different sizes<br> for n in range(1, 4):<br>  # 使用拉普拉斯算子<br>  kernel_size = 1+(n*2)<br>  gray_lap = cv2.Laplacian(gray_img, cv2.CV_16S, ksize=kernel_size)</pre><pre># Convert image format to uint8<br>  abs_lap = cv2.convertScaleAbs(gray_lap)</pre><pre># display image<br>  cv2.imshow(f&quot;{1+n*2}_lap_img&quot;,abs_lap)<br>  cv2.waitKey(0)<br>  cv2.destroyAllWindows()</pre><pre># save image<br>  cv2.imwrite(f&quot;./result/Laplacian/Laplacian_{1+n*2}.png&quot;,abs_lap)</pre><pre>if __name__ == &quot;__main__&quot;:<br> main()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lLG2VXkzuCk6dwRGnrHbag.png" /><figcaption>result</figcaption></figure><h3>Sobal operator</h3><h4>Principle</h4><p>The following picture is the mask used by the Sobal operator. <strong>The left side</strong> is for edge detection in <strong>the horizontal direction</strong>, and <strong>the right side</strong> is for edge detection in <strong>the vertical direction</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*rWAP_4pEIeNj7bxZxzrG-A.png" /></figure><p>Then use this mask the image to get the edge image.</p><h4>Implement</h4><p>Just like the Laplacian operator, openCV also provides written Sobal functions.</p><pre>dst = cv2.Sobel(src, ddepth, dx, dy, ksize)</pre><blockquote><em>src : the image to be processed.<br></em><em>dst : output image.<br></em><em>ddepth : The depth of the image. There are many flags that can be used. The most commonly used ones are </em><em>cv2.CV_8U and </em><em>cv2.CV_16S.<br></em><em>dx,</em><em> dy : It is to select the operation to be performed in the horizontal or vertical direction, and choose </em><em>(1, 0) or </em><em>(0, 1).<br></em><em>ksize : the size of the mask.</em></blockquote><p>After the Sobal operation, a convertScaleAbs operation is usually performed to convert the image back to a format that can be displayed normally.</p><pre>dst = cv2.convertScaleAbs(src)</pre><h4>Sample program</h4><p>The specific code can be viewed on <a href="https://github.com/jeffrey0524/AAA/tree/main/article05">my github</a>.</p><pre>import cv2</pre><pre>def main():<br> # read image<br> gray_img = cv2.imread(&quot;./lenna.jpg&quot;, 0)<br> cv2.imshow(&quot;img&quot;,gray_img)</pre><pre># Try masks of different sizes<br> for n in range(1, 4):<br>  # use sobel operator<br>  kernel_size = 1+(n*2)<br>  x = cv2.Sobel(gray_img, cv2.CV_16S, 1, 0, ksize=kernel_size)<br>  y = cv2.Sobel(gray_img, cv2.CV_16S, 0, 1, ksize=kernel_size)</pre><pre>  # Convert image format to uint8<br>  absX = cv2.convertScaleAbs(x)<br>  absY = cv2.convertScaleAbs(y)</pre><pre>  # Add the results from both directions to form a complete contour<br>  dst = cv2.addWeighted(absX, 0.5, absY,0.5,0)</pre><pre>  # display image<br>  cv2.imshow(f&quot;{1+n*2}_x&quot;,absX)<br>  cv2.imshow(f&quot;{1+n*2}_y&quot;,absY)<br>  cv2.imshow(f&quot;{1+n*2}_x+y&quot;,dst)<br>  cv2.waitKey(0)<br>  cv2.destroyAllWindows()</pre><pre>  # save image<br>  cv2.imwrite(f&quot;./result/Sobal/Sobal_{1+n*2}_x.png&quot;,absX)<br>  cv2.imwrite(f&quot;./result/Sobal/Sobal_{1+n*2}_y.png&quot;,absY)<br>  cv2.imwrite(f&quot;./result/Sobal/Sobal_{1+n*2}_x+y.png&quot;,dst)</pre><pre>if __name__ == &quot;__main__&quot;:<br> main()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*vE32sDUEbsFb6yqxWD2RMw.png" /><figcaption>input</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-_egGMcsGKlDeMsPSZMVuA.png" /><figcaption>result(kernel size = 3)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c--7zgGQ6FIzmU5fiZOa8A.png" /><figcaption>result(kernel size = 5)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RVw3eu5sWPxjgz6O4u10Jg.png" /><figcaption>result(kernel size = 7)</figcaption></figure><h3>Done!</h3><p>Now you know how to use OpenCV to deal with the image, so just go try to do it by yourself. Thanks for your watching, If you like my article don’t forget to leave your clap or share it with your friend. Your appreciation is my motivation. — Jeffrey</p><blockquote>Co-Author:<a href="https://medium.com/u/a22bbf0a981c?source=post_page-----e82b0bedd02d--------------------------------">Y. S. Huang</a>, a master’s student studying AIVC and likes open-source, if you are interesting, go to check my <a href="https://github.com/tw-yshuang">Github</a>!</blockquote><h3>References</h3><p><a href="https://en.wikipedia.org/wiki/Sobel_operator">https://en.wikipedia.org/wiki/Sobel_operator</a></p><p><a href="https://www.youtube.com/watch?v=usBg5zbD2wU">(98) 數位影像處理_許志明_單元七 影像分割_Part 1 影像分割基本概念 — YouTube</a></p><p><a href="https://www.youtube.com/watch?v=RSDcvDFXei4">(98) 數位影像處理_許志明_單元七 影像分割_Part 2 孤立點、線檢測 — YouTube</a></p><p><a href="https://www.youtube.com/watch?v=yHah3EbKwOI">數位影像處理_許志明_單元七 影像分割_Part 3 基本邊緣偵測 — YouTube</a></p><p><a href="https://medium.com/%E9%9B%BB%E8%85%A6%E8%A6%96%E8%A6%BA/%E9%82%8A%E7%B7%A3%E5%81%B5%E6%B8%AC-%E7%B4%A2%E4%BC%AF%E7%AE%97%E5%AD%90-sobel-operator-95ca51c8d78a">邊緣偵測 — 索伯算子 ( Sobel Operator ) — 電腦視覺 — Medium</a></p><p><a href="https://medium.com/%E9%9B%BB%E8%85%A6%E8%A6%96%E8%A6%BA/%E9%82%8A%E7%B7%A3%E5%81%B5%E6%B8%AC-%E6%8B%89%E6%99%AE%E6%8B%89%E6%96%AF%E7%AE%97%E5%AD%90-laplacian-operator-ea877f1945a0">邊緣偵測 — 拉普拉斯算子 ( Laplacian Operator ) — 電腦視覺 — Medium</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29aa84a8fd60" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ntust-aivc/digital-image-processing-edge-detection-29aa84a8fd60">Digital Image Processing : Edge Detection</a> was originally published in <a href="https://medium.com/ntust-aivc">NTUST-AIVC</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Digital Image Processing: Fourier Transform]]></title>
            <link>https://medium.com/ntust-aivc/opencv-fourier-transform-d9811aaac2d5?source=rss-c7e6b810b895------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9811aaac2d5</guid>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[dft]]></category>
            <dc:creator><![CDATA[Jeffrey]]></dc:creator>
            <pubDate>Sun, 17 Jul 2022 16:35:28 GMT</pubDate>
            <atom:updated>2023-07-25T16:12:13.287Z</atom:updated>
            <content:encoded><![CDATA[<p>The Fourier transform that an imaging engineer must know.</p><h3>Prolegomenon</h3><p>The meaning represented by the Fourier transform is: “Any periodic wave can be divided into many sine waves, and the meaning of the Fourier transform is to find the sine waves of each frequency”, and the same is true for images, By converting the image into sine waves of various frequencies, it can be converted or operated on, such as filtering out unwanted information through a filter. This is the practical application of the Fourier transform of the image, and it is also a must for image engineers. the reason for the meeting.</p><h3>Contents</h3><p><a href="#0b6f">Prolegomenon</a><br><a href="#a9c1">Principle</a><br><a href="#e6c7">Implement</a><br><a href="#7656">Application</a><br><a href="#2ae7">About The Author</a><br><a href="#53f3">References</a></p><h3>Principle</h3><p>Here is just a little mention of the formula part, if you just want to know how to use it or feel that Fourier transform is too cumbersome, you can skip to the next part!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*2zAG2AVB6vemBfZeaFEbpQ.png" /><figcaption>Definition of one-dimensional continuous Fourier transform</figcaption></figure><p>This is the most original definition of Fourier transform, which is used to transform continuous signals, but the picture is not a continuous analog signal, but a discrete digital signal, so we use the following discrete Fourier transform to transform the picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/209/1*JSwTnN5zGwy4STJx_ZBbZQ.png" /><figcaption>Definition of one-dimensional discrete Fourier transform</figcaption></figure><p>This is a one-dimensional Fourier transform, but the image we want to convert is two-dimensional, so a two-dimensional Fourier transform should be used, but if you directly write a two-dimensional Fourier transform, the amount of calculation will be too large, so in practice, we will perform a Fourier transform on the data vertically and horizontally to achieve the effect of a two-dimensional Fourier transform. Similarly, the inverse Fourier transform can also be achieved in the same way. Therefore, the formula for the two-dimensional conversion will not be repeated here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*wDmdSmHpfRm012f8lxKm6Q.png" /><figcaption>The left is the original image, and the right is the frequency distribution map after Fourier transformation</figcaption></figure><h3>Implement</h3><h4>Fourier Transform</h4><p>There are already ready-made fast Fourier transform functions available in the opencv and numpy suites in python, and the result of the transformation is a complex np.ndarray. The following are the various Fourier transform functions provided by numpy:</p><pre>#One-dimensional Fourier transform<br>numpy.fft.fft(src, n=None, axis=-1, norm=None)<br><br>#Two-dimensional Fourier transform<br>numpy.fft.fft2(src, n=None, axis=-1, norm=None)<br><br>#n-dimensional Fourier transform<br>numpy.fft.fftn()</pre><blockquote><em>src represents the input image, a numpy array, and only this parameter can be input.<br></em><em>n represents a sequence of integers that can determine the size of the output array, where n[0] represents axis 0 and n[1] represents axis 1. If the given shape is smaller than the input shape, the output will be clipped. If it is greater than it will be filled with zeros.<br></em><em>axes represents a sequence of integers, optional axes for computing the FFT. Repeated indices in “axes” mean that multiple transformations are performed for that axis, and a sequence of elements means that a 1D FFT is performed.<br></em><em>norm includes two options, None and ortho, normalization mode, and the default value is None.<br>See </em><a href="https://numpy.org/doc/stable/reference/generated/numpy.fft.fft.html"><em>the official website</em></a><em> for more details.</em></blockquote><p>Opencv also provides the following fast Fourier transform functions. Note that <strong>the input image must be converted to np.float32 format first</strong>. And it is the same result with numpy API, but it is <strong>two-channel</strong>, the first channel is the real part of the result, and the second channel is the imaginary part of the result.</p><pre>dst = cv2.dft(src, dst=None, flags=None, nonzeroRows=None)</pre><blockquote><em>src represents the input image, which </em><strong><em>needs to be in </em></strong><strong><em>np.float32 format</em></strong><em>. Can only input this parameter.<br></em><em>dst represents the output image, including output size and dimensions.<br>flags represents the transition flags, where:<br>● </em><em>DFT_INVERSE performs the reverse transformation instead of the preset forward transformation;<br>●</em><em>DFT_SCALE represents the scaling result, divided by the number of array elements;<br>●</em><em>DFT_ROWS This flag can transform multiple vectors in the forward or reverse direction at the same time, and can be used to reduce overhead when performing higher-dimensional transformations;<br>●</em><em>DFT_COMPLEX_OUTPUT performs forward conversion, the fastest choice, the default is this;<br>●</em><em>DFT_REAL_OUTPUT performs the inverse transform of a complex array, the result is usually a complex array of the same size, and if the input array has conjugate complex symmetry, the output is a real array.<br></em><em>nonzeroRows means that this function can handle and make it more efficient when when some specific argument is not zero.<br>See </em><a href="https://docs.opencv.org/4.x/d2/de8/group__core__array.html#gadd6cf9baf2b8b704a11b5f04aaf4f39d"><em>the official website</em></a><em> for more details.</em></blockquote><h4>Show Conversion Result</h4><p><strong>Fourier theory assumes the Fourier spectrum is periodic and is an infinite image repeating itself infinitely in both directions</strong>. It is usually shifted to show the result of the Fourier transform. <strong>The shift is to move the low-frequency information to the center point</strong>, so we can more easily to described the Fourier spectrum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ZxIJifAFxIvgBM1h5my5g.png" /><figcaption>https://www.cs.auckland.ac.nz/courses/compsci773s1c/lectures/ImageProcessing-html/topic1.htm</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*5q2w9CQFaiNV0DzeSnCZ9w.png" /><figcaption><a href="https://staff-old.najah.edu/sites/default/files/Chapter4_Frequency_Enhancement.pdf">https://staff-old.najah.edu/sites/default/files/Chapter4_Frequency_Enhancement.pdf</a></figcaption></figure><p>Using the following function to transfer to the middle position:</p><pre>np.fft.fftshift(fft_img)</pre><p>In addition, because the result after Fourier transformation is a complex number, the absolute value function of numpy is also used to calculate the amplitude of the complex number, and some numerical adjustments are usually made.</p><pre>10 * np.log(np.abs(fft_shift) + 1)</pre><blockquote><em>fft_shift is the result after shifting.<br></em><em>np.abs() is to take vibration.<br></em><em>+1 to avoid errors when log reaches log 0.<br></em><em>np.log() is numpy’s log function.<br>Taking the log multiplied by 10 is to adjust the value between 0 and 255. I suggest that the previous 10 can be adjusted to 15 or 20 depending on the difference in value.</em></blockquote><p>Opencv also provides another function to take vibration.</p><pre>cv2.magnitude(x, y, magnitude=None)</pre><blockquote><em>x represents the floating-point X coordinate value, that is, the real part.<br></em><em>y represents the floating-point Y coordinate value, that is, the imaginary part.</em></blockquote><h4>Inverse Fourier Transform</h4><p>When you want to convert the transformed or processed result back to the original image, numpy and opencv also provide related functions. The result can be obtained through a similar process but the process is reversed from that of the positive conversion.</p><pre>np.fft.ifftshift(fft_shift)</pre><pre># Inverse Fourier Transform<br>cv2.idft(fft_ishift)<br>     # or<br>np.fft.ifft2(fft_ishift)</pre><p>In the end, the sample program:</p><pre>import cv2<br>import numpy as np<br><br>path = &#39;Lenna.jpg&#39;<br>img = cv2.imread(path, 0)<br>cv2.imshow(&quot;orgin:&quot;, img)</pre><pre>f = np.fft.fft2(img)<br>fs = np.fft.fftshift(f)<br>lfs = 15 * np.log(1 + np.abs(fs))<br>cv2.imshow(&quot;dft:&quot;, np.uint8(lfs))</pre><pre>ishift_img = np.fft.ifftshift(fs)<br>ifft_img = np.fft.ifft2(ishift_img)<br>abs_img = np.abs(ifft_img)<br>cv2.imshow(&quot;idft:&quot;,np.uint8(abs_img))</pre><pre>cv2.waitKey(0)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X_O5ocLyBSYO1gv0wzcHsg.png" /><figcaption>Results</figcaption></figure><h3>Application</h3><p>After learning how to use Fourier transform, the next step is to enter the most important part, using Fourier transform to make various filters. The following is an example of the most simple and easy-to-understand high and<strong> low pass filters</strong>.</p><h4>Low Pass Filter</h4><p>After we get the Fourier spectrum, it represents the sine waves that build the image. <strong>The center of the image is low frequency</strong>, and<strong> the surrounding area is high frequency</strong>. Knowns that implementing a low-pass filter is to mask the surrounding image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H2O_yKfqGyWbi9QH5dw0-A.png" /><figcaption>low pass filter</figcaption></figure><p>The result after the inverse transformation is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EcZBTflCq2S3nPdAek_IHg.png" /></figure><h4>High Pass Filter</h4><p>Contrary to the low-pass filter, the image in the center after Fourier can be masked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OQ5KxgnxIkXMJhzMNwpLrg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2NxMPFB5sTNny8uyNpJygg.png" /></figure><p>For example, image denoising, image enhancement and sharpening, etc., also use similar principles as the basic processing of image processing, which shows the importance of Fourier Transform to image processing.</p><h3>Done!</h3><p>Now you know how to use OpenCV to deal with the image, so just go try to do it by yourself. Thanks for your watching, If you like my article don’t forget to leave your clap or share it with your friend. Your appreciation is my motivation. — Jeffrey</p><blockquote>Co-Author: <a href="https://medium.com/u/a22bbf0a981c">Y. S. Huang</a>, a master’s student studying AIVC, likes open-source.<br>If you are interested, go to check my <a href="https://github.com/tw-yshuang">Github</a>!</blockquote><h3><strong>Reference</strong></h3><ul><li><a href="https://iter01.com/551722.html">OpenCV計算機視覺學習（10）--影像變換（傅立葉變換，高通濾波，低通濾波）</a></li><li><a href="https://en.wikipedia.org/wiki/Fourier_transform">Fourier transform - Wikipedia</a></li></ul><p><a href="https://en.wikipedia.org/wiki/Discrete_Fourier_transform">https://en.wikipedia.org/wiki/Discrete_Fourier_transform</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9811aaac2d5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ntust-aivc/opencv-fourier-transform-d9811aaac2d5">Digital Image Processing: Fourier Transform</a> was originally published in <a href="https://medium.com/ntust-aivc">NTUST-AIVC</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Digital Image Processing: Read, Write, Show.]]></title>
            <link>https://medium.com/ntust-aivc/python-opencv-and-numpy-are-easy-to-use-in-a-few-steps-35684b3149ac?source=rss-c7e6b810b895------2</link>
            <guid isPermaLink="false">https://medium.com/p/35684b3149ac</guid>
            <category><![CDATA[image]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[numpy]]></category>
            <dc:creator><![CDATA[Jeffrey]]></dc:creator>
            <pubDate>Wed, 01 Jun 2022 18:35:20 GMT</pubDate>
            <atom:updated>2022-12-19T08:21:39.040Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*sVN2KSom9auxK0wZSgtUmA.png" /></figure><h4><strong>OpenCV</strong> and <strong>Numpy</strong>, using python to do image recognition must know how to use it.</h4><h3>What is OpenCV? Why learn it?</h3><p><strong>OpenCV</strong>, the full name of <strong>Open Source Computer Vision Library</strong>, is an image processing suite for python, written in <strong>C++</strong> and packaged in <strong>NumPy</strong>, so it is faster than other suites. Therefore, it has become <strong>the basis for learning image processing</strong>. If you want to learn how to use python to change your photos or videos, or if you want to use python to import a large number of images to train AI, just read on.</p><h3>Contents</h3><p><strong>What is OpenCV? Why learn it?<br>Why Numpy?<br> Install<br> how to use<br> ●Read pictures<br> ●Save pictures<br> ●Display pictures</strong></p><h3>Why Numpy?</h3><p>OpenCV has been introduced above, and here we mainly introduce why it should be used with Numpy. As mentioned earlier, openCV is <strong>encapsulated by NumPy</strong> on python; that is to say, <strong>the formats of OpenCV and NumPy are common</strong>, and the images read by openCV are <strong>stored in NumPy arrays</strong>. You can use type command to confirm it.</p><h3>Install</h3><p>Before starting to use it, it is necessary to install it properly.</p><ol><li>Open your terminal and enter the following commands.</li></ol><pre>pip install numpy opencv-python</pre><p>or</p><pre>pip install opencv-python</pre><p>There is no need to additionally install numpy, because it is already included when installing opencv.</p><blockquote><em>General python is pre-installed with pip3, so you can use it directly. If you are a user who has installed the </em><em>pipenv mentioned in the previous article, you can enter the virtual environment and change the previous pip to </em><em>pipenv input.</em></blockquote><p>More details can be found in my previous article.</p><p><a href="https://medium.com/ntust-aivc/how-to-install-pyenv-pipenv-in-ubuntu-and-use-multiple-versions-of-python-and-its-suites-3514099a6e05">How to install pyenv+pipenv in ubuntu and use multiple versions of python and its suites</a></p><p>2. Before start using them, you also need to import them into the program.</p><p>Type these commands at the top of your code:</p><pre>import numpy as np<br>import cv2</pre><blockquote><em>Usually, numpy is abbreviated to </em><em>np for use, and some people will abbreviated </em><em>cv2 to </em><em>cv.</em></blockquote><p>Then you can start using them in the program! As for how to use them, keep reading!</p><h3>How to use it?</h3><p>After it is finally installed, let’s introduce the various functions of OpenCV!</p><h4>Read image</h4><p>Use the imread function to read images, which can be thought of as a shorthand for image read, which is easier to remember.</p><pre>img = cv2.imread(path, flag)</pre><blockquote><strong><em>path</em></strong><em> is the image path variable you want to read. Note that you should </em><strong><em>enclose the path with</em></strong><strong><em>‘ ‘</em></strong><em>when declaring it, and remember to add the filename extension, such as </em><em>&#39;input.jpg&#39;.</em></blockquote><blockquote><strong><em>flag</em></strong><em> is to determine the format of the image to be read, or </em><strong><em>it can be omitted</em></strong><em>. There are the following three types:<br> </em><em>cv2.IMREAD_UNCHANGED or </em><em>-1 : read all channels in the image, including transparency.<br> </em><em>cv2.IMREAD_GRAYSCALE or </em><em>0 : read in grayscale format.<br> </em><em>cv2.IMREAD_COLOR or </em><em>1 : (default) read in BGRformat.</em></blockquote><blockquote><strong><em>img</em></strong><em> is a variable that stores an image. It has been said before that the type will be a numpy array; if the input image format is preset, three colors of </em><strong><em>BGR</em></strong><em> will be stored in the variable, and the dimension is </em><strong><em>three-dimensional</em></strong><em> (note that the order cannot be changed, if you want to use other software to display the order); if the format of image is gray, it will using grayscale format, also mean that it’s dimension will be </em><strong><em>two-dimensional</em></strong><em>.</em></blockquote><h4>Save image</h4><p>Use the imwrite function to save images, like imread, which can be thought of as a shorthand for image write/save.</p><pre>cv2.imwrite(path, img, params)</pre><blockquote><strong><em>path</em></strong><em> is a variable that stores the path of the archive. Note that when declaring it, </em><strong><em>enclose the path with </em></strong><strong><em>‘ ‘</em></strong><em>, and remember to</em><strong><em> add the filename extension</em></strong><em>. This </em><strong><em>important</em></strong><em> so I say it again.</em></blockquote><blockquote><strong><em>img</em></strong><em> is a variable that holds the image to be output.</em></blockquote><blockquote><strong><em>params</em></strong><em> is the parameter of the storage type, and it </em><strong><em>can be added or not</em></strong><em>. There are 17 kinds in total, See the following website for details.</em></blockquote><p><a href="https://docs.opencv.org/4.x/d8/d6a/group__imgcodecs__flags.html#gga61d9b0126a3e57d9277ac48327799c80af660544735200cbe942eea09232eb822">OpenCV: Flags used for image file reading and writing</a></p><h4>Show image</h4><p>Use the imshow function to display the picture. If you want to remember it, I don’t need to say more.</p><pre>cv2.imshow(“windows”, img)</pre><blockquote><strong><em>“windows”</em></strong><em> is the displayed window name.<br></em><strong><em>img</em></strong><em> is a variable that holds the image to be output.</em></blockquote><p>Usually, these two lines of instructions are followed after the image is displayed.</p><pre>cv2.waitKey(delay)<br>cv2.destroyAllWindows()</pre><blockquote><strong><em>waitKey</em></strong><em> is to wait for the user to input after displaying the picture, or you can use the returned value to get the ASCII code value </em><em>key = cv2.waitKey(delay).</em></blockquote><blockquote><strong><em>destroyAllWindows</em></strong><em> will close the window after receiving input. You can also use </em><em>cv2.destroyWindow(“windows”) to close the specified window.</em></blockquote><h3>Done!</h3><p>Now you know how to use OpenCV to deal with the image, so just go try to do it by yourself. Thanks for your watching, If you like my article don’t forget to leave your clap or share it with your friend. Your appreciation is my motivation. —Jeffrey</p><blockquote>Co-Author: <a href="https://medium.com/u/a22bbf0a981c">Y. S. Huang</a>, a master’s student studying AIVC, likes open-source.<br>If you are interested, go to check my <a href="https://github.com/tw-yshuang">Github</a>!</blockquote><h3>References</h3><ul><li><a href="https://medium.com/ching-i/python-opencv-%E8%AE%80%E5%8F%96%E9%A1%AF%E7%A4%BA%E5%8F%8A%E5%84%B2%E5%AD%98%E5%BD%B1%E5%83%8F-%E5%BD%B1%E7%89%87-ee3701c454da">Python-OpenCV — 讀取顯示及儲存影像、影片</a></li><li><a href="https://www.ithome.com.tw/voice/144703">從NumPy到OpenCV</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35684b3149ac" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ntust-aivc/python-opencv-and-numpy-are-easy-to-use-in-a-few-steps-35684b3149ac">Digital Image Processing: Read, Write, Show.</a> was originally published in <a href="https://medium.com/ntust-aivc">NTUST-AIVC</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to install pyenv+pipenv in ubuntu and use multiple versions of python and its suites]]></title>
            <link>https://medium.com/ntust-aivc/how-to-install-pyenv-pipenv-in-ubuntu-and-use-multiple-versions-of-python-and-its-suites-3514099a6e05?source=rss-c7e6b810b895------2</link>
            <guid isPermaLink="false">https://medium.com/p/3514099a6e05</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pipenv]]></category>
            <category><![CDATA[pip]]></category>
            <category><![CDATA[pyenv]]></category>
            <dc:creator><![CDATA[Jeffrey]]></dc:creator>
            <pubDate>Thu, 31 Mar 2022 13:49:04 GMT</pubDate>
            <atom:updated>2023-07-16T10:01:56.117Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*Y9qW6gufh8hNBolY4ll0LA.png" /></figure><h4>Let pyenv and pipenv help you write python better</h4><blockquote>Co-Author: <a href="https://medium.com/u/a22bbf0a981c">Y. S. Huang</a>, a master’s student studying AIVC, likes open-source.<br>If you are interested, go to check my <a href="https://github.com/tw-yshuang">Github</a>!</blockquote><h3>Content</h3><h4><strong>pyenv</strong></h4><p><a href="#e8c8">Why do we need multiple versions of python?</a></p><p><a href="#0ff8">How to install </a><a href="#0ff8">pyenv?</a></p><p><a href="#b3c4">How to use </a><a href="#b3c4">pyenv?</a></p><h4>pipenv</h4><p><a href="#ae14">Why do you need </a><a href="#ae14">pipenv?</a></p><p><a href="#855e">What is </a><a href="#855e">pipenv?</a></p><p><a href="#aca3">How to install </a><a href="#aca3">pipenv?</a></p><p><a href="#975f">How to use </a><a href="#975f">pipenv?</a></p><p><a href="#c366"><strong>Why use </strong></a><a href="#c366"><strong>pyenv+</strong></a><a href="#c366"><strong>pipenv?</strong></a></p><p><a href="#a0eb">References</a></p><h3>Why do we need multiple versions of python?</h3><p>As an engineer, you may face many projects at the same time, but each project may require <strong>different versions of python</strong>. At this time, as a qualified engineer, it is impossible to uninstall python every time you need to switch versions and reinstall. In this situation, you will need a tool that <strong>can install and switch different versions of python</strong>, this is the protagonist pyenv introduced today.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*nYCW2WoRAExNPgeZqtNdjA.png" /></figure><h3>How to install Pyenv?</h3><p>1. First we need to <strong>install git</strong> (if it is already installed, skip it)</p><pre>sudo apt-get install git</pre><p>2. Use apt-get to <strong>install related packages</strong></p><pre>sudo apt-get update; sudo apt-get install -y --no-install-recommends make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev</pre><p>3. Download pyenv from the official GitHub with git clone to install:</p><pre>git clone https://github.com/pyenv/pyenv.git ~/.pyenv</pre><p>4. This is <strong>the most important and error-prone step</strong>, allowing our terminal to use the instructions of pyenv. In this step, we need to <strong>make different settings according to the shell used by your terminal</strong>. The following is an example of <strong>the default </strong><strong>bash of Ubuntu</strong> and<strong> the </strong><strong>zsh used by the moderator</strong>:</p><h4>bash users: set .bashrc and .profile</h4><p>The simplest and most violent method is to directly copy and execute the following scripts:</p><pre>echo -e ‘if shopt -q login_shell; then’ \<br> ‘\n export PYENV_ROOT=”$HOME/.pyenv”’ \<br> ‘\n export PATH=”$PYENV_ROOT/bin:$PATH”’ \<br> ‘\n eval “$(pyenv init — path)”’ \<br> ‘\nfi’ &gt;&gt; ~/.bashrcecho -e ‘if [ -z “$BASH_VERSION” ]; then’\<br> ‘\n export PYENV_ROOT=”$HOME/.pyenv”’\<br> ‘\n export PATH=”$PYENV_ROOT/bin:$PATH”’\<br> ‘\n eval “$(pyenv init — path)”’\<br> ‘\nfi’ &gt;&gt;~/.profileecho ‘if command -v pyenv &gt;/dev/null; then eval “$(pyenv init -)”; fi’ &gt;&gt; ~/.bashrc</pre><p><strong>Finish!</strong></p><h4>zsh user: set ~/.zprofile and ~/.zshrc of zsh</h4><p>Simpler for zsh users:</p><pre>echo ‘export PYENV_ROOT=”$HOME/.pyenv”’ &gt;&gt; ~/.zprofile<br>echo ‘export PATH=”$PYENV_ROOT/bin:$PATH”’ &gt;&gt; ~/.zprofile<br>echo ‘eval “$(pyenv init — path) “‘ &gt;&gt; ~/.zprofile<br>echo ‘eval “$(pyenv init -)”’ &gt;&gt; ~/.zshrc</pre><p><strong>Finish!</strong></p><p>The first three lines of instructions mean adding the following text to the ~/.zprofile file</p><pre>export PYENV_ROOT=”$HOME/.pyenv<br>export PATH=”$PYENV_ROOT/bin:$PATH<br>eval “$(pyenv init — path)”</pre><p>The last line of instruction means to add the following text to the ~/.zshrc file</p><pre>eval “$(pyenv init -)”</pre><p>Of course, you can also open the file directly and paste these lines. However, if you are watching other teachings at the same time, <strong>be careful to delete the newly added text in other teachings first</strong>, and then paste these lines!</p><p>5. Finally, log in again, let the computer re-read the .zproflie file and you can use it. You can also use source ~/.profile or source ~/.zprofile for the computer to reload the config file again.</p><blockquote><strong><em>Possible errors:</em></strong></blockquote><blockquote><strong><em>zsh: command not found: pyenv</em></strong></blockquote><blockquote><em>This means that a few lines of instructions in .zprofile have not been executed. You can use the </em><em>source command to make the computer read. If it is still the same after re-login, you can put the text originally added to .zproflie into</em><em> .zshrc, and you can put the newly added </em><em>eval “$(pyenv init -)” is deleted, and finally the terminal can be re-executed.</em></blockquote><blockquote><em>If you want to know the execution order of </em><em>~/.profile and </em><em>~/.zshrc, you can refer to the follow link down below, probably when you log in, </em><em>~/.zproflie, then </em><em>~/.zshrc will be executed when terminal is opened.</em></blockquote><blockquote><em>If jump out </em><em>ValueError: unknown locale: UTF-8 related errors.</em></blockquote><blockquote><em>This is due to a LANG error in</em><em>.zshrc,try changing it to the following</em></blockquote><blockquote>export LANG=en_US.utf-8</blockquote><p><a href="https://blog.miniasp.com/post/2021/07/26/Bash-and-Zsh-Initialization-Files">The Will Will Web</a></p><h3>How to use pyenv?</h3><h4>1. Check which Python versions are available</h4><p>To see which Python versions are available for installation, use the command pyenv install --list or pyenv install -l .</p><h4>2. Install Python</h4><p>Take creating a virtual environment for Python 3.8.12 as an example:</p><pre>pyenv install 3.8.12</pre><p>The message after execution is:</p><pre>Downloading Python-3.8.12.tar.xz…<br>-&gt; https://www.python.org/ftp/python/3.8.12/Python-3.8.12.tar.xz<br>Installing Python-3.8.12…</pre><p>Just wait for it to install.</p><h4>3. Set 3.8.12 as the Python version in use</h4><pre>pyenv global 3.8.12</pre><p>3.8.12 can be replaced with any version you have installed</p><blockquote><em>The so-called “global” here is only valid for the current user’s shell. In addition, the board owner does not recommend using the </em><em>pyenv local &lt;python-version&gt;command here, because using local may lead to the wrong location when using the virtual environment to install the package later. Of course, if you very clearly know what kind of environment you want a locate, then enjoy using it!</em></blockquote><h4>4. Check the version of python and pyenv</h4><p>View the currently available python version that has been installed (there will be a * in front of it):</p><pre>pyenv versions</pre><p>Check out the current python version in use:</p><pre>pyenv version</pre><p>Check the current version of pyenv in use:</p><pre>pyenv --version</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*86PFmNIaaxvf70ywZr_D6g.png" /><figcaption>I am using python 3.10.3 here</figcaption></figure><h3>Why do you need pipenv?</h3><p>As a qualified engineer, you will find that in addition to Python itself, there are many versions, and even <strong>the packages under python will have many versions</strong>, but pyenv can’t handle so many. What should I do at this time? And in the process of collaborating with other engineers, you will also need to co-work on a project. Is there has an easy way to <strong>transfer it along with the packages</strong> it needs?<br>At this time, you need pipenv to save yourself from repeated uninstallation and installation.</p><h3>What is pipenv?</h3><p>It integrates<strong> </strong>pip3 and virtualenv<strong> </strong>into one. It has both functions and better optimization so that you can <strong>create a virtual environment</strong> under python with a single command by using pipenv to install python’s specified packages and many more. Things and <strong>the various virtual environments</strong> will <strong>not affect each other</strong>. The most important thing is that a version directory file is automatically generated. When handing over the work, as long as it is delivered together with the program file, the other party will know what version of python and packages should be used, and let Pipenv install it automatically.</p><h3>How to install pipenv?</h3><p>Here is the pip3 with the latest python3</p><pre>sudo apt-get install python3-pip</pre><p>After installation, you can use the command to check the version of the pip/pip3</p><pre>pip --version</pre><p>Use this command to see what packages you have installed</p><pre>pip list</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*qViOm6YG99o45z-G8YDbuw.png" /><figcaption>Usually, there are a lot of things installed in the system by default.</figcaption></figure><p>Usually, there are a lot of things installed in the system by default.<br>Next use pip to install pipenv</p><pre>pip install pipenv</pre><h4>Finish!</h4><p>Compared with pyenv it is much simpler. Finally, use the following command to confirm the version you installed.</p><pre>pipenv --version</pre><h3>How to use pipenv?</h3><h4>Create a virtual environment</h4><p>In the desired path, using pipenv to create a virtual environment of the python version you want to use, take python 3.8.6 as an example:</p><pre>pipenv --python 3.8.6</pre><p>At this time, if there is no <strong>Pipfile</strong> file in the directory, pipenv will automatically generate a <strong>Pipfile</strong> to record the installed packages, the content is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*eCqChU5WfESa712LuggzsA.png" /></figure><h4>Enter the virtual environment</h4><p>Execute the following command to enter the virtual environment</p><pre>pipenv shell</pre><p>If you are also using <strong>oh-my-zsh with powerlevel10k</strong>, the name of <strong>the virtual environment should appear in the upper right corner of the command</strong>, indicating that you have entered the virtual environment</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*m1fTIRqJl2HqKcCRrAaX8A.png" /><figcaption>the name of the virtual environment should appear in the upper right corner of the command</figcaption></figure><p>If you want, you can also install <a href="https://github.com/gangleri/oh-my-zsh/tree/pipenv_plugin/plugins/pipenv"><strong>plugins of pipenv</strong></a><strong> </strong>on oh-my-zsh<strong> </strong>so that you can manipulate the pipenv easier &amp; faster.</p><h3>Install the desired package</h3><p>Install the desired package in the virtual environment, taking NumPy as an example</p><pre>pipenv install numpy</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*kwjgRNCeLvpaPzZyu8eg6Q.png" /></figure><p>Install a specific version of the package:</p><pre>pipenv install numpy==1.16.5</pre><p>Uninstall unwanted packages:</p><pre>pipenv uninstall numpy</pre><p>After the installation is complete, the ./pipfile will also change:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*PeOeZoGdy17HIiv6kbQ7pg.png" /><figcaption>One more line of numpy this is the installed suite</figcaption></figure><blockquote><em>If you accidentally install an error when using </em><em>pipenv install, such as typing the wrong package name or the package name does not exist, etc,.<br>At this point you usually change the name and download it again, right? But you will find that even though the name of the kit is correct this time, the same error message will still be sprayed! ! !<br>This is because even if the last package name cannot be downloaded due to the wrong name, </em><em>pipenv still adds the wrong package name to the </em><strong><em>Pipfile</em></strong><em> file, and because the package that is not installed in </em><strong><em>Pipflie</em></strong><em> will be installed before downloading the new package this time. The new package will be installed, at which point </em><em>pipenv will be forced to download the package with the wrong name again…<br>The solution is: directly rewrite the </em><strong><em>Pipfile</em></strong><em> file and remove the wrong package name! ! ! Or use pipenv uninstall with the wrong package name. Uninstalling the package will also automatically remove the wrong package name in the Pipfile! ! !</em></blockquote><blockquote><em>If the error is that the pip related instructions cannot be found in the virtual environment, you can use </em><em>python get-pip.py — force-reinstall to reinstall pip, so that it can be used.</em></blockquote><p><em>Taken from:</em></p><p>In addition, after the package is installed, a <strong>pipfile.lock</strong> file will be generated, which is the file that stores all the required package settings. Just pass this file to the cooperating engineer, and he can use the pipenv sync command to All required kits can be installed.</p><h4>Exit the virtual environment</h4><p>Press CTRL + D or hit exit to exit the virtual environment.</p><h4>Delete virtual environment</h4><p>To delete the virtual environment, execute pipenv --rm command.</p><h3>Why use pyenv+pipenv?</h3><p>pyenv allows <strong>each version of python </strong>on our computer to be managed separately, and pipenv can <strong>create a new independent package-space</strong> under each python version, allowing you to install the required packages in it so that each things in <strong>the space are independent of each other</strong> and do not affect each other. It’s easier to manage and much more organized. When you want to change the suite, <strong>the scope of the impact will only be limited to that small space</strong>, and will not cause too much complexity when you make changes in the future due to the lack of organized management because of too many things installed. You need to reload the computer directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*PpFIErhZBj-sb5hwcGZEDQ.png" /></figure><h3>References</h3><ul><li><a href="https://medium.com/@chihsuan/pipenv-%E6%9B%B4%E7%B0%A1%E5%96%AE-%E6%9B%B4%E5%BF%AB%E9%80%9F%E7%9A%84-python-%E5%A5%97%E4%BB%B6%E7%AE%A1%E7%90%86%E5%B7%A5%E5%85%B7-135a47e504f4">Pipenv 更簡單、更快速的 Python 套件管理工具</a></li><li><a href="https://medium.com/@hiimdoublej/pipenv%E6%8C%87%E4%BB%A4%E5%A4%A7%E5%85%A8-6e4415cc8a15">Pipenv指令大全</a></li><li><a href="https://medium.com/citycoddee/python-%E5%B7%A5%E5%85%B7%E7%AE%B1-1-%E5%B0%88%E6%A1%88%E5%BF%85%E5%82%99-pipenv-a517e292f6c">Python 工具箱 (1) — 專案必備 Pipenv</a></li><li><a href="https://blog.kyomind.tw/ubuntu-pyenv/">Ubuntu 安裝使用 pyenv + pyenv-virtualenv</a></li></ul><p><a href="https://ithelp.ithome.com.tw/articles/10250782">https://ithelp.ithome.com.tw/articles/10250782</a></p><p><a href="https://josix.tw/pyenv-deep-dive/#path-%E7%92%B0%E5%A2%83%E8%AE%8A%E6%95%B8">https://josix.tw/pyenv-deep-dive/#path-%E7%92%B0%E5%A2%83%E8%AE %8A%E6%95%B8</a></p><p><a href="https://blog.miniasp.com/post/2021/07/26/Bash-and-Zsh-Initialization-Files">The Will Will Web</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3514099a6e05" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ntust-aivc/how-to-install-pyenv-pipenv-in-ubuntu-and-use-multiple-versions-of-python-and-its-suites-3514099a6e05">How to install pyenv+pipenv in ubuntu and use multiple versions of python and its suites</a> was originally published in <a href="https://medium.com/ntust-aivc">NTUST-AIVC</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[在Ubuntu中安裝Pipenv並以此建構虛擬環境來在Python下使用多種版本的套件]]></title>
            <link>https://medium.com/@b10932006/%E5%9C%A8ubuntu%E4%B8%AD%E5%AE%89%E8%A3%9Dpipenv%E4%B8%A6%E4%BB%A5%E6%AD%A4%E5%BB%BA%E6%A7%8B%E8%99%9B%E6%93%AC%E7%92%B0%E5%A2%83%E4%BE%86%E5%9C%A8python%E4%B8%8B%E4%BD%BF%E7%94%A8%E5%A4%9A%E7%A8%AE%E7%89%88%E6%9C%AC%E7%9A%84%E5%A5%97%E4%BB%B6-821961ac6752?source=rss-c7e6b810b895------2</link>
            <guid isPermaLink="false">https://medium.com/p/821961ac6752</guid>
            <category><![CDATA[pip]]></category>
            <category><![CDATA[pipenv]]></category>
            <category><![CDATA[ubuntu-20-04]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Jeffrey]]></dc:creator>
            <pubDate>Thu, 31 Mar 2022 13:15:18 GMT</pubDate>
            <atom:updated>2022-03-31T13:15:18.641Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zm8F8oOtI_oQvDxtbMXW0Q.jpeg" /></figure><p>python工程師必裝的軟件</p><h3>為什麼需要pipenv?</h3><p>作為一個合格的工程師，你會發現除了Python本身有多種版本，連python下面的套件都會有許多的版本，但Pyenv卻管不了那麼多，那這時候該怎麼辦呢？而且在與其他工程師協作的過程中，還會需要交接程式碼，有沒有什麼辦法可以連同其所需的套件一同傳輸呢？</p><p>這時候你就需要Pipenv來拯救你於反覆的卸載安裝了</p><p>這篇文章是繼我的上一篇文章pyenv的延伸，沒看過的可以先去瀏覽一下。</p><p><a href="https://medium.com/@b10932006/%E5%A6%82%E4%BD%95%E5%9C%A8ubuntu%E4%B8%AD%E5%AE%89%E8%A3%9Dpyenv%E4%B8%A6%E4%BD%BF%E7%94%A8%E5%A4%9A%E7%A8%AE%E7%89%88%E6%9C%AC%E7%9A%84python-6626c1fbc76e">如何在ubuntu中安裝pyenv並使用多種版本的python？</a></p><h3>什麼是Pipenv？</h3><p>他<strong>整合了 pip 及 virtualenv 於一體</strong>，兼具兩者的功能的同時還做了更好的優化，讓你可以以pipenv一個指令就實現在python下面<strong>創建虛擬環境</strong>，<strong>安裝python的指定套件</strong>等等許多的事情，而且各個虛擬環境之間還不會互相影響。最重要的是還會<strong>自動產生一個版本目錄檔</strong>，要交接工作的時候，只要連同程式檔一同交付，對方就會知道應該使用什麼版本的python與套件，並讓Pipenv自動安裝。</p><h3>如何安裝Pipenv？</h3><h4>首先安裝pip</h4><p>這裡是用最新的python3所配合的pip3</p><pre>sudo apt-get install python3-pip</pre><p>安裝好後，可以用指令來查看pip的版本</p><pre>pip --version</pre><p>用這個指令可以查看自己安裝了什麼套件</p><pre>pip list</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*qViOm6YG99o45z-G8YDbuw.png" /><figcaption>通常在system下預設都會裝有很多東西了</figcaption></figure><h4>接下來用pip來安裝pipenv</h4><pre>sudo pip install pipenv</pre><h4>完成</h4><p>相比起pyenv簡單很多吧，最後使用下列指令來確認你安裝的版本巴</p><pre>pipenv --version</pre><h3>如何使用Pipenv？</h3><ul><li>創建虛擬環境</li></ul><p>首先想要的路徑中，創建虛擬環境pipenv --python 想要使用的python版本，以python 3.8.6舉例：</p><pre>pipenv --python 3.8.6</pre><p>此時，若目錄下無 Pipfile檔，Pipenv 會自動產生一個 Pipfile，用來記錄所安裝的套件，內容如下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*eCqChU5WfESa712LuggzsA.png" /></figure><ul><li>進入虛擬環境</li></ul><p>執行下面這行指令即可進入虛擬環境</p><pre>pipenv shell</pre><p>如果你也是使用zsh，那麼指令的右上角應該會出現虛擬環境的名子，代表你進入虛擬環境了</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*m1fTIRqJl2HqKcCRrAaX8A.png" /><figcaption>右上角那個藍色的Aproject...就是虛擬環境名稱</figcaption></figure><p>如有想要，也可以另裝其他插件使得進入此資料夾的時候，自動進入虛擬環境。</p><ul><li>安裝想要的套件</li></ul><p>在虛擬環境中安裝想要的套件，以numpy舉例</p><pre>pipenv install numpy</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*kwjgRNCeLvpaPzZyu8eg6Q.png" /></figure><p>安裝特定版本的套件：</p><pre>pipenv install numpy==1.16.5</pre><p>解除安裝不想要的套件：</p><pre>pipenv uninstall numpy</pre><p>安裝完成之後，pipfile檔也會跟著改變</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*PeOeZoGdy17HIiv6kbQ7pg.png" /><figcaption>多了一行numpy這就是所安裝的套件</figcaption></figure><blockquote><em>如果在使用 </em><em>pipenv install 時不小心安裝錯誤，例如打錯套件名稱或是套件名稱不存在等</em></blockquote><blockquote><em>此時通常你會再把名稱改對之後再下載一次對吧？但你會發現，儘管這次套件名稱打對了，依舊會噴一模一樣的 error message！！！</em></blockquote><blockquote><em>這是因為即使上次的套件名稱因為打錯名稱無法下載，pipenv 仍然把上一次書入錯誤的套件名稱加入 </em><em>Pipfile 檔，又因為這次下載新套件前都會把 </em><em>Pipflie 裡面的未安裝的套件再安裝好才會安裝新套件，此時 pipenv 就會被迫再一次的下載名稱錯誤的套件……</em></blockquote><blockquote><strong><em>解法就是：直接去改寫 </em></strong><strong><em>Pipfile 檔，把該錯誤的套件名稱拿掉！！！或是使用 </em></strong><strong><em>pipenv uninstall 錯誤套件名稱 卸載套件同時也會自動移除 </em></strong><strong><em>Pipfile 檔中的錯誤套件名！！！</em></strong></blockquote><blockquote>取自:<a href="https://medium.com/citycoddee/python-%E5%B7%A5%E5%85%B7%E7%AE%B1-1-%E5%B0%88%E6%A1%88%E5%BF%85%E5%82%99-pipenv-a517e292f6c">https://medium.com/citycoddee/python-%E5%B7%A5%E5%85%B7%E7%AE%B1-1-%E5%B0%88%E6%A1%88%E5%BF%85%E5%82%99-pipenv-a517e292f6c</a></blockquote><blockquote><em>如果出現的錯誤是在虛擬環境中找不到pip相關指令的話可以使用</em><em>python get-pip.py --force-reinstall來重新安裝pip，這樣就可以用了。</em></blockquote><p>另外，安裝好套件之後，還會產生一個pipfile.lock檔，這就是儲存了所有所需套件設定的檔案，只需要將這個檔案一同傳給協作的工程師，就可以讓他用pipenv sync一指令就可以安裝全部所需套件。</p><ul><li>退出虛擬環境</li></ul><p>按 CTRL + D 或打 exit，即可退出虛擬環境。</p><pre>exit</pre><ul><li>刪除虛擬環境</li></ul><p>若想刪除該虛擬環境，就可執行這條指令。</p><pre>pipenv --rm</pre><h3>為什麼要用pyenv+pipenv?</h3><p>Pyenv 可以讓我們電腦上每個版本的python都分開來管理，而pipenv可以在每個python的版本下面，創立一個新的空間，讓你在裡面安裝需要的套件，如此下來，就可以讓每一個空間裡的東西互相獨立出來，互不影響。管理起來也就方便，有條理很多了。想要改變套件的時候，影響的範圍也會僅止於那個小空間，而不會造成因為裝了太多東西，又卻乏有條理的管理，讓未來進行變更的時候，太過於複雜，而需要直接重灌電腦。</p><h3>參考資料：</h3><ul><li><a href="https://medium.com/@chihsuan/pipenv-%E6%9B%B4%E7%B0%A1%E5%96%AE-%E6%9B%B4%E5%BF%AB%E9%80%9F%E7%9A%84-python-%E5%A5%97%E4%BB%B6%E7%AE%A1%E7%90%86%E5%B7%A5%E5%85%B7-135a47e504f4">Pipenv 更簡單、更快速的 Python 套件管理工具</a></li><li><a href="https://medium.com/@hiimdoublej/pipenv%E6%8C%87%E4%BB%A4%E5%A4%A7%E5%85%A8-6e4415cc8a15">Pipenv指令大全</a></li><li><a href="https://medium.com/citycoddee/python-%E5%B7%A5%E5%85%B7%E7%AE%B1-1-%E5%B0%88%E6%A1%88%E5%BF%85%E5%82%99-pipenv-a517e292f6c">Python 工具箱 (1) — 專案必備 Pipenv</a></li></ul><p><a href="https://ithelp.ithome.com.tw/articles/10250782">https://ithelp.ithome.com.tw/articles/10250782</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=821961ac6752" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[如何在ubuntu中安裝pyenv並使用多種版本的python？]]></title>
            <link>https://medium.com/@b10932006/%E5%A6%82%E4%BD%95%E5%9C%A8ubuntu%E4%B8%AD%E5%AE%89%E8%A3%9Dpyenv%E4%B8%A6%E4%BD%BF%E7%94%A8%E5%A4%9A%E7%A8%AE%E7%89%88%E6%9C%AC%E7%9A%84python-6626c1fbc76e?source=rss-c7e6b810b895------2</link>
            <guid isPermaLink="false">https://medium.com/p/6626c1fbc76e</guid>
            <dc:creator><![CDATA[Jeffrey]]></dc:creator>
            <pubDate>Wed, 23 Mar 2022 07:20:32 GMT</pubDate>
            <atom:updated>2022-03-23T11:08:21.201Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*bhmf2hlnvQ5DZoB9-baFSg.jpeg" /></figure><h3>為什麼需要多種版本的python?</h3><p>作為一個工程師，可能會同時面臨到許多的project，但每個project都可能會要求使用不同版本的python才能編輯，這時作為一個合格的工程師，總不可能每次需要切換版本的時候就將python卸載重裝，所以這時候就會需要一個軟體可以安裝與切換不同版本的python，這就是今天介紹的主角Pyenv。</p><h3>如何安裝Pyenv?</h3><p>1.首先我們需要先安裝git（如已安裝可跳過</p><pre>sudo apt-get install git</pre><p>2.使用apt-git安裝相關套件</p><pre>sudo apt-get update; sudo apt-get install -y --no-install-recommends make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev</pre><p>3.以git clone從官方github下載pyenv並安裝：</p><pre>git clone https://github.com/pyenv/pyenv.git ~/.pyenv</pre><p>4.這是最重要也是最容易出錯的一步，讓我們的terminal可以使用pyenv的指令。<strong>在這步驟中，我們需要根據自己terminal使用的shell做不同的設定</strong>，以下以ubuntu預設的bash舉例跟版主使用的zsh作介紹：</p><h4>bash 用戶：設定.bashrc與.profile</h4><p>最簡單暴力的方法就是直接複製並執行下面這幾段 script：</p><pre><strong>echo</strong> -e &#39;if shopt -q login_shell; then&#39; \<br>      &#39;\n  export PYENV_ROOT=&quot;$HOME/.pyenv&quot;&#39; \<br>      &#39;\n  export PATH=&quot;$PYENV_ROOT/bin:$PATH&quot;&#39; \<br>      &#39;\n eval &quot;$(pyenv init --path)&quot;&#39; \<br>      &#39;\nfi&#39; &gt;&gt; ~/.bashrc</pre><pre><strong>echo</strong> -e &#39;if [ -z &quot;$BASH_VERSION&quot; ]; then&#39;\<br>      &#39;\n  export PYENV_ROOT=&quot;$HOME/.pyenv&quot;&#39;\<br>      &#39;\n  export PATH=&quot;$PYENV_ROOT/bin:$PATH&quot;&#39;\<br>      &#39;\n  eval &quot;$(pyenv init --path)&quot;&#39;\<br>      &#39;\nfi&#39; &gt;&gt;~/.profile</pre><pre><strong>echo</strong> &#39;if command -v pyenv &gt;/dev/null; then eval &quot;$(pyenv init -)&quot;; fi&#39; &gt;&gt; ~/.bashrc</pre><p><strong>完成！</strong></p><h4>zsh 用戶：設定 zsh 的.zprofile、.zshrc</h4><p>zsh用戶的比較簡單:</p><pre><strong>echo</strong> &#39;export PYENV_ROOT=&quot;$HOME/.pyenv&quot;&#39; &gt;&gt; ~/.zprofile</pre><pre><strong>echo</strong> &#39;export PATH=&quot;$PYENV_ROOT/bin:$PATH&quot;&#39; &gt;&gt; ~/.zprofile</pre><pre><strong>echo</strong> &#39;eval &quot;$(pyenv init --path)&quot;&#39; &gt;&gt; ~/.zprofile</pre><pre><strong>echo</strong> &#39;eval &quot;$(pyenv init -)&quot;&#39; &gt;&gt; ~/.zshrc</pre><p><strong>完成！</strong></p><p>前三行指令的意思就是在.zprofile這個檔案中新增以下文本</p><pre>export PYENV_ROOT=&quot;$HOME/.pyenv<br>export PATH=&quot;$PYENV_ROOT/bin:$PATH<br>eval &quot;$(pyenv init --path)&quot;</pre><p>最後一行指令的意思就是在.zshrc這個檔案中新增以下文本</p><pre>eval &quot;$(pyenv init -)&quot;</pre><p>當然，也可以直接開啟檔案並貼上這幾行字。不過，<strong>若同時有看其他教學，注意要先把其他教學中新增的文本刪除，再貼上這幾行噢！</strong></p><p>5.最後，重新登入，讓電腦重新讀取.zproflie檔案就可以使用了。也可以用source ~/.profile或 source ~/.zprofile讓電腦讀取。</p><blockquote><em>可能會出現的錯誤：</em></blockquote><blockquote><strong><em>zsh: command not found: pyenv</em></strong></blockquote><blockquote><em>這就是.zprofile中的幾行指令沒有被執行到，可以使用source指令讓電腦讀取，若重登入後還是一樣的話，可以把原本要加進.zproflie的文本放進.zshrc，並可以將剛新增的eval “$(pyenv init -)”刪掉，最後重新執行terminal即可。</em></blockquote><blockquote><em>若想知道.profile跟.zshrc的執行順序可以參考</em><a href="https://blog.miniasp.com/post/2021/07/26/Bash-and-Zsh-Initialization-Files"><em>https://blog.miniasp.com/post/2021/07/26/Bash-and-Zsh-Initialization-Files</em></a><em>，大概就是登入時會執行~/.zshproflie，然後開termail時會執行~/.zshrc。</em></blockquote><blockquote><em>可能會出現的錯誤2：</em></blockquote><blockquote><em>在打pyenv help時會出現很多行</em></blockquote><blockquote><em>line 29: warning: setlocale: LC_CTYPE: cannot change locale ©: No such file or directory — version Display the version of pyenv</em></blockquote><blockquote><em>或是跳出 ValueError: unknown locale: UTF-8 相關錯誤</em></blockquote><blockquote><em>這是由於.zshrc中的LANG錯誤導致，將其改成以下即可</em></blockquote><blockquote><em>export LANG=en_US.utf-8</em></blockquote><h3><em>如何使用pyenv?</em></h3><h4>一、查看有哪些Python版本可供使用</h4><p>要查看有哪些 Python 版本可供安裝，可使用指令pyenv install --list或pyenv install -l查詢</p><h4>二、安裝 Python</h4><p>以建立 Python 3.8.12 的虛擬環境為例：</p><pre>pyenv install 3.8.12</pre><p>執行後的訊息為：</p><pre>Downloading Python-3.8.12.tar.xz…<br>-&gt; <a href="https://www.python.org/ftp/python/3.8.12/Python-3.8.12.tar.xz">https://www.python.org/ftp/python/3.8.12/Python-3.8.12.tar.xz</a><br>Installing Python-3.8.12…</pre><p>慢慢等它安裝即可。</p><h4>二、將 3.8.12 設為使用中的 Python 版本</h4><pre>pyenv global 3.8.12</pre><p>3.8.12可以替換成任意你安裝的版本</p><blockquote><em>這裡所謂的「global（全域）」</em><strong><em>只對當前使用者的 shell 有效</em></strong><em>，另外板主在這裡並不建議使用local指令，因為使用local可能會使後面使用虛擬環境安裝套件時，會導向錯誤的位置。</em></blockquote><h4>三、查看python與pyenv的版本</h4><p>查看已安裝好目前可用的python版本(使用中前面會有個*)：</p><pre>pyenv versions</pre><p>查看當前使用的python版本：</p><pre>pyenv version</pre><p>查看當前使用的pyenv版本：</p><pre>pyenv --version</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*86PFmNIaaxvf70ywZr_D6g.png" /><figcaption>我這裡是使用3.10.3的python</figcaption></figure><h3>參考資料：</h3><p>Ubuntu 安裝使用 pyenv + pyenv-virtualenv：<a href="https://blog.kyomind.tw/ubuntu-pyenv/">https://blog.kyomind.tw/ubuntu-pyenv/</a></p><p>建立一個方便開發的 Python 環境 （零）- 使用 Pyenv 管理 Python 版本：<a href="https://josix.tw/pyenv-deep-dive/#path-%E7%92%B0%E5%A2%83%E8%AE%8A%E6%95%B8">https://josix.tw/pyenv-deep-dive/#path-%E7%92%B0%E5%A2%83%E8%AE%8A%E6%95%B8</a></p><p>關於 Linux 下 Bash 與 Zsh 啟動檔的載入順序研究：<a href="https://blog.miniasp.com/post/2021/07/26/Bash-and-Zsh-Initialization-Files">https://blog.miniasp.com/post/2021/07/26/Bash-and-Zsh-Initialization-Files</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6626c1fbc76e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>